Introduction
JavaScript evolved in a very short time from callbacks to promises (ES2015), and since ES2017 asynchronous JavaScript is even simpler with the async/await syntax.
Async functions are a combination of promises and generators, and basically, they are a higher level abstraction over promises. Let me repeat: async/await is built on promises.
Useful Commands (internal use
)
npm i @stackbit/gatsby-plugin-menus babel-runtime chokidar classnames fs-extra gatsby gatsby-image gatsby-plugin-netlify gatsby-plugin-netlify-cms gatsby-plugin-sass gatsby-plugin-react-helmet gatsby-plugin-typescript --legacy-peer-deps
git checkout 307a5cd # check out the commit that you want to reset to
git checkout -b fixy # create a branch named fixy to do the work
git merge -s ours master # merge master's history without changing any files
git checkout master # switch back to master
git merge fixy # and merge in the fixed branch
git push # done, no need to force push!
Web Dev Setup
Web Dev Setup
title: WebDev Setup template: post subtitle: Basic Web Development Environment Setup excerpt: Windows Subsystem for Linux (WSL) and Ubuntu date: 2022-05-08T18:10:03.296Z image: https://cdn-images-1.medium.com/max/800/0aqKP1drNHmNm34zz.jpg thumb_image: https://cdn-images-1.medium.com/max/800/0aqKP1drNHmNm34zz.jpg image_position: right author: src/data/authors/bgoonz.yaml categories: - src/data/categories/js.yaml - src/data/categories/javascript.yaml tags: - src/data/tags/links.yaml - src/data/tags/resources.yaml show_author_bio: true related_posts: - src/pages/blog/vs-code-extensions.md - src/pages/blog/code-playgrounds-of-2021.md - src/pages/blog/adding-css-to-your-html.md - src/pages/blog/deploy-react-app-to-heroku.md cmseditable: true
Basic Web Development Environment Setup
Windows Subsystem for Linux (WSL) and Ubuntu
Basic Web Development Environment Setup
Windows Subsystem for Linux (WSL) and Ubuntu
1. In the application search box in the bottom bar, type "PowerShell" to find the application named "Windows PowerShell"
2. Right-click on "Windows PowerShell" and choose "Run as administrator" from the popup menu
3. In the blue PowerShell window, type the following: `Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux`
4. Restart your computer
5. In the application search box in the bottom bar, type "Store" to find the application named "Microsoft Store"
6. Click "Microsoft Store"
7. Click the "Search" button in the upper-right corner of the window
8. Type in "Ubuntu"
9. Click "Run Linux on Windows (Get the apps)"
10. Click the orange tile labeled **"Ubuntu"** Note that there are 3 versions in the Microsoft Store⊠you want the one just entitled 'Ubuntu'
11. Click "Install"
12. After it downloads, click "Launch"
13. If you get the option, pin the application to the task bar. Otherwise, right-click on the orange Ubuntu icon in the task bar and choose "Pin to taskbar"
14. When prompted to "Enter new UNIX username", type your first name with no spaces
15. When prompted, enter and retype a password for this UNIX user (it can be the same as your Windows password)
16. Confirm your installation by typing the command `whoami 'as in who-am-i'`followed by Enter at the prompt (it should print your first name)
17. You need to update your packages, so type `sudo apt update` (if prompted for your password, enter it)
18. You need to upgrade your packages, so type `sudo apt upgrade` (if prompted for your password, enter it)
Git
Git comes with Ubuntu, so there's nothing to install. However, you should configure it using the following instructions.
Open an Ubuntu terminal if you don't have one open already.
-
You need to configure Git, so type
git config --global user.name "Your Name"with replacing "Your Name" with your real name. -
You need to configure Git, so type
git config --global user.email your@email.comwith replacing "your@email.com" with your real email.
Note: if you want git to remember your login credentials type:
git config --global credential.helper store
Google Chrome
Test if you have Chrome installed by typing "Chrome" in the search box in the bottom app bar that reads "Type here to search". If you see a search result that reads "Chrome" with "App" under it, then you have it installed. Otherwise, follow these instructions to install Google Chrome.
Node.js
Test if you have Node.js installed by opening an Ubuntu terminal and typing node
--version. If it reports "Command 'node' not found", then you need
to follow these directions.
-
In the Ubuntu terminal, type
sudo apt updateand press Enter -
In the Ubuntu terminal, type
sudo apt install build-essentialand press Enter -
In the Ubuntu terminal, type
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bashand press Enter -
In the Ubuntu terminal, type
. ./.bashrcand press Enter -
In the Ubuntu terminal, type
nvm install --ltsand press Enter -
Confirm that node is installed by typing
node --versionand seeing it print something that is not "Command not found"!
Unzip
You will often have to download a zip file and unzip it. It is easier to do this from the command line. So we need to install a linux unzip utility.
In the Ubuntu terminal type: sudo apt install unzip and press Enter
Mocha.js
Test if you have Mocha.js installed by opening an Ubuntu terminal and typing which
mocha. If it prints a path, then you're good. Otherwise, if it prints nothing,
install Mocha.js by typing npm install -g mocha.
Python 3
Ubuntu does not come with Python 3. Install it using the command sudo apt install
python3. Test it by typing python3 --version and seeing it print a
number.
Note about WSL
As of the time of writing of this document, WSL has an issue renaming or deleting files if Visual Studio Code is open. So before doing any linux commands which manipulate files, make sure you close Visual Studio Code before running those commands in the Ubuntu terminal.
Some other common instillations
# Installing build essentials
sudo apt-get install -y build-essential libssl-dev
# Nodejs and NVM
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
source ~/.profile
sudo nvm install 7.10.0
sudo nvm use 7.10.0
node -v
#nodemon
sudo npm install -g nodemon
sudo npm install -g loopback-cli
# Forever to run nodejs scripts forever
sudo npm install forever -g
# Git - a version control system
sudo apt-get update
sudo apt-get install -y git xclip
# Grunt - an automated task runner
sudo npm install -g grunt-cli
# Bower - a dependency manager
sudo npm install -g bower
# Yeoman - for generators
sudo npm install -g yo
# maven
sudo apt-get install maven -y
# Gulp - an automated task runner
sudo npm install -g gulp-cli
# Angular FullStack - My favorite MEAN boilerplate (MEAN = MongoDB, Express, Angularjs, Nodejs)
sudo npm install -g generator-angular-fullstack
# Vim, Curl, Python - Some random useful stuff
sudo apt-get install -y vim curl python-software-properties
sudo apt-get install -y python-dev, python-pip
sudo apt-get install -y libkrb5-dev
# Installing JDK and JRE
sudo apt-get install -y default-jre
sudo apt-get install -y default-jdk
# Archive Extractors
sudo apt-get install -y unace unrar zip unzip p7zip-full p7zip-rar sharutils rar uudeview mpack arj cabextract file-roller
# FileZilla - a FTP client
sudo apt-get install -y filezilla
Documentation Commands:
documentation build src/components/DocsMenu.js -f md> ./notes/DocsMenu.md documentation build src/components/Footer.js -f md> ./notes/Footer.md documentation build src/components/Header.js -f md> ./notes/Header.md documentation build src/components/index.js -f md> ./notes/index.md documentation build src/components/SectionContent.js -f md> ./notes/SectionContent.md documentation build src/components/SectionDocs.js -f md> ./notes/SectionDocs.md documentation build src/components/SectionHero.js -f md> ./notes/SectionHero.md documentation build src/components/CtaButtons.js -f md> ./notes/CtaButtons.md documentation build src/components/DocsSubmenu.js -f md> ./notes/DocsSubmenu.md documentation build src/components/FormField.js -f md> ./notes/FormField.md documentation build src/components/Icon.js -f md> ./notes/Icon.md documentation build src/components/Layout.js -f md> ./notes/Layout.md documentation build src/components/SectionCta.js -f md> ./notes/SectionCta.md documentation build src/components/SectionGrid.js -f md> ./notes/SectionGrid.md documentation build src/components/Submenu.js -f md> ./notes/Submenu.md documentation build src/components/ActionLink.js -f md> ./notes/ActionLink.md
Blog Content
:
Bash Cheat Sheet (MY COMMANDS
)
Bash Cheat Sheet (MY COMMANDS) </summary
1. Remove spaces from file and folder names and then remove numbers from files and folder names
Description: need to : sudo apt install
rename
Notes: Issue when renaming file without numbers collides with existing file name...
code
find . -name "* *" -type d | rename 's/ /_/g'
find . -name "* *" -type f | rename 's/ /_/g'
```bash
find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh
find $dir -type d | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh
for i in *.html; do mv "$i" "${i%-*}.html"; done
for i in *.*; do mv "$i" "${i%-*}.${i##*.}"; done
---
### Description: combine the contents of every file in the contaning directory.
>Notes: this includes the contents of the file it's self...
###### code:
```js
//APPEND-DIR.js
const fs = require('fs');
let cat = require('child_process')
.execSync('cat *')
.toString('UTF-8');
fs.writeFile('output.md', cat, err => {
if (err) throw err;
});
2. Download Website Using Wget
Description
Notes: ==> sudo apt install wget
code
wget --limit-rate=200k --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla https://bootcamp42.gitbook.io/python/
3. Clean Out Messy Git Repo
Description: recursively removes git related folders as well as internal use files / attributions in addition to empty folders
Notes: To clear up clutter in repositories that only get used on your local machine.
code
find . -empty -type d -print -delete
find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} +
find . \( -name "*SECURITY.txt" -o -name "*RELEASE.txt" -o -name "*CHANGELOG.txt" -o -name "*LICENSE.txt" -o -name "*CONTRIBUTING.txt" -name "*HISTORY.md" -o -name "*LICENSE" -o -name "*SECURITY.md" -o -name "*RELEASE.md" -o -name "*CHANGELOG.md" -o -name "*LICENSE.md" -o -name "*CODE_OF_CONDUCT.md" -o -name "*CONTRIBUTING.md" \) -exec rm -rf -- {} +
4. clone all of a user's git repositories
Description: clone all of a user or organization's git repositories
Notes:
code
Generalized
CNTX={users|orgs}; NAME={username|orgname}; PAGE=1
curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=100" |
grep -e 'git_url*' |
cut -d \" -f 4 |
xargs -L1 git clone
Clone all Git User
CNTX={users}; NAME={bgoonz}; PAGE=1
curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master |
grep -e 'git_url*' |
cut -d \" -f 4 |
xargs -L1 git clone
Clone all Git Organization
CNTX={organizations}; NAME={TheAlgorithms}; PAGE=1
curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master |
grep -e 'git_url*' |
cut -d \" -f 4 |
xargs -L1 git clone
5. Git Workflow
Description
code
git pull
git init
git add .
git commit -m"update"
git push -u origin master
git init
git add .
git commit -m"update"
git push -u origin main
git init
git add .
git commit -m"update"
git push -u origin bryan-guner
git init
git add .
git commit -m"update"
git push -u origin gh-pages
git init
git add .
git commit -m"update"
git push -u origin preview
6. Recursive Unzip In Place
Description: recursively unzips folders and then deletes the zip file by the same name
Notes:
code
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;
find . -name "*.zip" -type f -print -delete
7. git pull keeping local changes
Description
Notes:
code
git stash
git pull
git stash pop
8. Prettier Code Formatter
Description
Notes:
code
sudo npm i prettier -g
prettier --write .
9. Pandoc
Description
Notes:
code
find ./ -iname "*.md" -type f -exec sh -c 'pandoc --standalone "${0}" -o "${0%.md}.html"' {} \;
find ./ -iname "*.html" -type f -exec sh -c 'pandoc --wrap=none --from html --to markdown_strict "${0}" -o "${0%.html}.md"' {} \;
find ./ -iname "*.docx" -type f -exec sh -c 'pandoc "${0}" -o "${0%.docx}.md"' {} \;
10. Gitpod Installs
Description
Notes:
code
sudo apt install tree
sudo apt install pandoc -y
sudo apt install rename -y
sudo apt install black -y
sudo apt install wget -y
npm i lebab -g
npm i prettier -g
npm i npm-recursive-install -g
black .
prettier --write .
npm-recursive-install
11. Repo Utils Package
Description: my standard repo utis package
Notes:
code
npm i @bgoonz11/repoutils
12. Unix Tree Package Usage
Description
Notes:
code
tree -d -I 'node_modules'
tree -I 'node_modules'
tree -f -I 'node_modules' >TREE.md
tree -f -L 2 >README.md
tree -f -I 'node_modules' >listing-path.md
tree -f -I 'node_modules' -d >TREE.md
tree -f >README.md
13. Find & Replace string in file & folder names recursively
Description
Notes:
code
find . -type f -exec rename 's/string1/string2/g' {} +
find . -type d -exec rename 's/-master//g' {} +
find . -type f -exec rename 's/\.download//g' {} +
find . -type d -exec rename 's/-main//g' {} +
rename 's/\.js\.download$/.js/' *.js\.download
rename 's/\.html\.markdown$/.md/' *.html\.markdown
find . -type d -exec rename 's/es6//g' {} +
14. Remove double extensions
Description
Notes:
code
#!/bin/bash
for file in *.md.md
do
mv "${file}" "${file%.md}"
done
#!/bin/bash
for file in *.html.html
do
mv "${file}" "${file%.html}"
done
#!/bin/bash
for file in *.html.png
do
mv "${file}" "${file%.png}"
done
for file in *.jpg.jpg
do
mv "${file}" "${file%.png}"
done
15. Truncate folder names down to 12 characters
Description: Truncate folder names down to 12 characters
Notes: Truncate folder names down to 12 characters
code
for d in ./*; do mv $d ${d:0:12}; done
16.Appendir.js
Description: combine the contents of every file in the contaning directory
Notes: this includes the contents of the file it's self...
code
//APPEND-DIR.js
const fs = require('fs');
let cat = require('child_process').execSync('cat *').toString('UTF-8');
fs.writeFile('output.md', cat, (err) => {
if (err) throw err;
});
17. Replace space in filename with underscore
Description: followed by replace
'#' with '_' in directory name
Notes: Can be re-purposed to find and replace any set of strings in file or folder names.
code
find . -name "* *" -type f | rename 's/_//g'
find . -name "* *" -type d | rename 's/#/_/g'
18. Filter & delete files by name and extension
Description
Notes:
code
find . -name '.bin' -type d -prune -exec rm -rf '{}' +
find . -name '*.html' -type d -prune -exec rm -rf '{}' +
find . -name 'nav-index' -type d -prune -exec rm -rf '{}' +
find . -name 'node-gyp' -type d -prune -exec rm -rf '{}' +
find . -name 'deleteme.txt' -type f -prune -exec rm -rf '{}' +
find . -name 'right.html' -type f -prune -exec rm -rf '{}' +
find . -name 'left.html' -type f -prune -exec rm -rf '{}' +
19. Remove lines containing string
Description
Notes: Remove lines not containing
'.js'
sudo sed -i '/\.js/!d' ./*scrap2.md
code
sudo sed -i '/githubusercontent/d' ./*sandbox.md
sudo sed -i '/githubusercontent/d' ./*scrap2.md
sudo sed -i '/github\.com/d' ./*out.md
sudo sed -i '/author/d' ./*
20. Remove duplicate lines from a text file
Description
Notes: //...syntax of uniq...// $uniq [OPTION] [INPUT[OUTPUT]] The syntax of this is quite easy to understand. Here, INPUT refers to the input file in which repeated lines need to be filtered out and if INPUT isn't specified then uniq reads from the standard input. OUTPUT refers to the output file in which you can store the filtered output generated by uniq command and as in case of INPUT if OUTPUT isn't specified then uniq writes to the standard output.
Now, let's understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq.
code
sudo apt install uniq
uniq -u input.txt output.txt
21. Remove lines containing string
Description
Notes:
code
sudo sed -i '/githubusercontent/d' ./*sandbox.md
sudo sed -i '/githubusercontent/d' ./*scrap2.md
sudo sed -i '/github\.com/d' ./*out.md
---
title: add_days
tags: date,intermediate
firstSeen: 2020-10-28T16:19:04+02:00
lastUpdated: 2020-10-28T16:19:04+02:00
---
sudo sed -i '/title:/d' ./*output.md
sudo sed -i '/firstSeen/d' ./*output.md
sudo sed -i '/lastUpdated/d' ./*output.md
sudo sed -i '/tags:/d' ./*output.md
sudo sed -i '/badstring/d' ./*
sudo sed -i '/stargazers/d' ./repo.txt
sudo sed -i '/node_modules/d' ./index.html
sudo sed -i '/right\.html/d' ./index.html
sudo sed -i '/right\.html/d' ./right.html
22. Zip directory excluding .git and node_modules all the way down (Linux
)
Descriptio: zip up an entire git directory
Notes:
code
`bash
#!/bin/bash
TSTAMP=date '+%Y%m%d-%H%M%S'
zip -r $1.$TSTAMP.zip $1 -x ".git/*" -x "node_modules/*"
shift; echo $@;
printf "\nCreated: $1.$TSTAMP.zip\n"
usage
:
- zipdir thedir
- zip thedir -x "anotherexcludedsubdir" (important the double quotes to prevent glob expansion
)
if in windows/git-bash, add 'zip' command this way
:
https://stackoverflow.com/a/55749636/1482990
`
23. Delete files containing a certain string
Description
Notes:
code
find . | xargs grep -l www.redhat.com | awk '{print "rm "$1}' > doit.sh
vi doit.sh // check for murphy and his law
source doit.sh
24 Generate sitemap
Description
Notes: bash command to auto generate sitemap.html which will list all files contained within parent directory.
code
`bash
#!/bin/sh
find ./ | grep -i "\.*$" >files
find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i ".*$">files listing="files"
out=""
html="index.html" out="basename $out.html" html="index.html" cmd() {
echo ' <!DOCTYPE html>' echo '' echo '
'echo ' '
echo ' ' echo ' ' echo ' ' echo ' '
echo "
echo "" echo '' echo ''
echo '
'echo ""
continue with the HTML stuff
echo ""
echo ""
echo "
- "
- "};
{print " <a href=\""$1"\">",$1,"
"}' \ $listing
awk '{print "<iframe src=\""$1"\">",""}' $listing
awk '{print "
echo ""
echo "
echo " "
echo " "
}
cmd $listing --sort=extension >>$html
`
25. Index of Iframes
Description: Creates an index.html file that contains all the files in the working directory or any of it's sub folders as iframes instead of anchor tags
Notes: Useful Follow up Code:
code
`bash
#!/bin/sh
26. Filter Corrupted Git Repo For Troublesome File
Description
Notes:
code
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch assets/_index.html' HEAD
27. OVERWRITE LOCAL CHANGES
Description
Important: If you have any local changes, they will be lost. With or without --hard option, any local commits that haven't been pushed will be lost.[*] If you have any files that are not tracked by Git (e.g. uploaded user content), these files will not be affected.
Notes: First, run a fetch to update all origin/
refs to latest:
code
`bash
git fetch --all
Backup your current branch
:
git branch backup-master
Then, you have two options
:
git reset --hard origin/master
OR If you are on some other branch
:
git reset --hard origin/<branch_name>
Explanation
:
git fetch downloads the latest from remote without trying to merge or rebase anything
.
Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master
git fetch --all git reset --hard origin/master
`
28. Remove Submodules
Description: To remove a submodule you need to
Notes:
Delete the relevant section from the .gitmodules file. Stage the .gitmodules changes git add .gitmodules Delete the relevant section from .git/config. Run git rm --cached path_to_submodule (no trailing slash). Run rm -rf .git/modules/path_to_submodule (no trailing slash). Commit git commit -m "Removed submodule " Delete the now untracked submodule files rm -rf path_to_submodule
code
git submodule deinit
29. GET GISTS
Description
Notes:
code
sudo apt install wget
wget -q -O - https://api.github.com/users/bgoonz/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget
wget -q -O - https://api.github.com/users/amitness/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget
wget -q -O - https://api.github.com/users/drodsou/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget
wget -q -O - https://api.github.com/users/thomasmb/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget
30. Remove Remote OriginL
Description
Notes:
code
git remote remove origin
31. just clone .git folder
Description
Notes:
code
git clone --bare --branch=master --single-branch https://github.com/bgoonz/My-Web-Dev-Archive.git
32. Undo recent pull request
Description
Notes:
code
git reset --hard master@{"10 minutes ago"}
33. Lebab
Description: ES5 --> ES6
Notes:
code
`bash
Safe
:
lebab --replace ./ --transform arrow lebab --replace ./ --transform arrow-return lebab --replace ./ --transform for-of lebab --replace ./ --transform for-each lebab --replace ./ --transform arg-rest lebab --replace ./ --transform arg-spread lebab --replace ./ --transform obj-method lebab --replace ./ --transform obj-shorthand lebab --replace ./ --transform multi-var
ALL
:
lebab --replace ./ --transform obj-method lebab --replace ./ --transform class lebab --replace ./ --transform arrow lebab --replace ./ --transform let lebab --replace ./ --transform arg-spread lebab --replace ./ --transform arg-rest lebab --replace ./ --transform for-each lebab --replace ./ --transform for-of lebab --replace ./ --transform commonjs lebab --replace ./ --transform exponent lebab --replace ./ --transform multi-var lebab --replace ./ --transform template lebab --replace ./ --transform default-param lebab --replace ./ --transform destruct-param lebab --replace ./ --transform includes lebab --replace ./ --transform obj-method lebab --replace ./ --transform class lebab --replace ./ --transform arrow lebab --replace ./ --transform arg-spread lebab --replace ./ --transform arg-rest lebab --replace ./ --transform for-each lebab --replace ./ --transform for-of lebab --replace ./ --transform commonjs lebab --replace ./ --transform exponent lebab --replace ./ --transform multi-var lebab --replace ./ --transform template lebab --replace ./ --transform default-param lebab --replace ./ --transform destruct-param lebab --replace ./ --transform includes
`
34. Troubleshoot Ubuntu Input/Output Error
Description: Open Powershell as Administrator
Notes:
code
wsl.exe --shutdown
Get-Service LxssManager | Restart-Service
35. Export Medium as Markdown
Description
Notes:
code
npm i mediumexporter -g
mediumexporter https://medium.com/codex/fundamental-data-structures-in-javascript-8f9f709c15b4 >ds.md
36. Delete files in violation of a given size range (100MB for git
)
Description
Notes:
code
find . -size +75M -a -print -a -exec rm -f {} \;
find . -size +98M -a -print -a -exec rm -f {} \;
37. download all links of given file type
Description
Notes:
code
wget -r -A.pdf https://overapi.com/git
38. Kill all node processes
Description
Notes:
code
killall -s KILL node
39. Remove string from file names recursively
Description: In the example below I am using this command to remove the string "-master" from all file names in the working directory and all of it's sub directories
code
find <mydir> -type f -exec sed -i 's/<string1>/<string2>/g' {} +
find . -type f -exec rename 's/-master//g' {} +
Notes: The same could be done for folder names by changing the -type f flag (for file) to a -type d flag (for directory)
find <mydir> -type d -exec sed -i 's/<string1>/<string2>/g' {} +
find . -type d -exec rename 's/-master//g' {} +
40. Remove spaces from file and folder names recursively
Description: replaces spaces in
file and folder names with an _ underscore
Notes: need to run
sudo apt install renameto use this command
code
find . -name "* *" -type d | rename 's/ /_/g'
find . -name "* *" -type f | rename 's/ /_/g'
41. Zip Each subdirectories in a given directory into their own zip file
Description
Notes:
code
for i in */; do zip -r "${i%/}.zip" "$i"; done
91. Unzip PowerShell
Description
Notes:
code
PARAM (
[string] $ZipFilesPath = "./",
[string] $UnzipPath = "./RESULT"
)
$Shell = New-Object -com Shell.Application
$Location = $Shell.NameSpace($UnzipPath)
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
$progress = 1
foreach ($ZipFile in $ZipFiles) {
Write-Progress -Activity "Unzipping to $($UnzipPath)" -PercentComplete (($progress / ($ZipFiles.Count + 1)) * 100) -CurrentOperation $ZipFile.FullName -Status "File $($Progress) of $($ZipFiles.Count)"
$ZipFolder = $Shell.NameSpace($ZipFile.fullname)
$Location.Copyhere($ZipFolder.items(), 1040) # 1040 - No msgboxes to the user - https://msdn.microsoft.com/library/bb787866%28VS.85%29.aspx
$progress++
}
92. return to bash from zsh
Description
Notes:
code
sudo apt --purge remove zsh
93. Symbolic Link
Description: to working directory
Notes:
code
ln -s "$(pwd)" ~/NameOfLink
ln -s "$(pwd)" ~/Downloads
94. auto generate readme
Description: rename existing readme to blueprint.md
Notes:
code
npx @appnest/readme generate
95. Log into postgres
Description
Notes:
code
sudo -u postgres psql
96. URL To Subscribe To YouTube Channel
Description
var declarations, wherever they occur, are processed before any code is executed. This is called
hoisting, and is discussed further below.
The scope of a variable declared with var is its current execution context and closures
thereof, which is either the enclosing function and functions declared within it, or, for variables
declared outside any function, global. Duplicate variable declarations using var will not trigger
an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
'use strict';
function foo() {
var x = 1;
function bar() {
var y = 2;
console.log(x); // 1 (function `bar` closes over `x`)
console.log(y); // 2 (`y` is in scope)
}
bar();
console.log(x); // 1 (`x` is in scope)
console.log(y); // ReferenceError in strict mode, `y` is scoped to `bar`
}
foo();
Variables declared using var are created before any code is executed in a process known as hoisting.
Their initial value is undefined.
'use strict';
console.log(x); // undefined (note: not ReferenceError)
console.log('still going...'); // still going...
var x = 1;
console.log(x); // 1
console.log('still going...'); // still going...
In the global context, a variable declared using var is added as a non-configurable property of the
global object. This means its property descriptor cannot be changed and it cannot be deleted using delete. The corresponding name is also added to a list on the
internal [[VarNames]] slot on the global
environment record (which forms part of the global lexical environment). The list of names in
[[VarNames]] enables the runtime to distinguish between global variables and straightforward
properties on the global object.
The property created on the global object for global variables, is set to be non-configurable because the
identifier is to be treated as a variable, rather than a straightforward property of the global object.
JavaScript has automatic memory management, and it would make no sense to be able to use the delete
operator on a global variable.
'use strict';
var x = 1;
globalThis.hasOwnProperty('x'); // true
delete globalThis.x; // TypeError in strict mode. Fails silently otherwise.
delete x; // SyntaxError in strict mode. Fails silently otherwise.
Note that in both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object.
Unqualified identifier assignments
The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope
chain is searched. This means that properties on the global object are conveniently visible from every scope,
without having to qualify the names with globalThis. or window. or
global..
So you can just type:
function foo() {
String('s') // Note the function `String` is implicitly visible
}
...because
globalThis.hasOwnProperty('String') // true
So the global object will ultimately be searched for unqualified identifiers. You don't have to type
globalThis.String, you can just type the unqualified String. The corollary, in
non-strict mode, is that assignment to unqualified identifiers will, if there is no variable of the same name
declared in the scope chain, assume you want to create a property with that name on the global object.
foo = 'f' // In non-strict mode, assumes you want to create a property named `foo` on the global object
globalThis.hasOwnProperty('foo') // true
In ECMAScript 5, this behavior was changed for strict mode. Assignment to an
unqualified identifier in strict mode will result in a ReferenceError, to avoid the accidental
creation of properties on the global object.
Note that the implication of the above, is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables, it merely has a syntax that looks like it does.
var hoisting
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
bla = 2;
var bla;
// ...is implicitly understood as:
var bla;
bla = 2;
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.
It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached:
function do_something() {
console.log(bar); // undefined
var bar = 111;
console.log(bar); // 111
}
// ...is implicitly understood as:
function do_something() {
var bar;
console.log(bar); // undefined
bar = 111;
console.log(bar); // 111
}
97. Embed Repl.it In Medium Post
code
https://repl.it/@bgoonz/Data-Structures-Algos-Codebase?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com
https://repl.it/@bgoonz/node-db1-project?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com
https://repl.it/@bgoonz/interview-prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com
https://repl.it/@bgoonz/Database-Prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com
98 rRmove text target="parent" from files called right.html
Description
Notes:
code
find . -name *right.html -type f -exec sed -i 's/target="_parent"//g' {} +
find . -name *right.html -type f -exec sed -i 's/target="_parent"//g' {} +
99. Cheat Sheet
Description
Notes:
code
`bash
#!/bin/bash revert
SHORTCUTS and HISTORY
CTRL+A # move to beginning of line CTRL+B # moves backward one character CTRL+C # halts the current command CTRL+D # deletes one character backward or logs out of current session, similar to exit CTRL+E # moves to end of line CTRL+F # moves forward one character CTRL+G # aborts the current editing command and ring the terminal bell CTRL+H # deletes one character under cursor (same as DELETE) CTRL+J # same as RETURN CTRL+K # deletes (kill) forward to end of line CTRL+L # clears screen and redisplay the line CTRL+M # same as RETURN CTRL+N # next line in command history CTRL+O # same as RETURN, then displays next line in history file CTRL+P # previous line in command history CTRL+Q # resumes suspended shell output CTRL+R # searches backward CTRL+S # searches forward or suspends shell output CTRL+T # transposes two characters CTRL+U # kills backward from point to the beginning of line CTRL+V # makes the next character typed verbatim CTRL+W # kills the word behind the cursor CTRL+X # lists the possible filename completions of the current word CTRL+Y # retrieves (yank) last item killed CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background
ALT+B # moves backward one word ALT+D # deletes next word ALT+F # moves forward one word ALT+H # deletes one character backward ALT+T # transposes two words ALT+. # pastes last word from the last command. Pressing it repeatedly traverses through command history. ALT+U # capitalizes every character from the current cursor position to the end of the word ALT+L # uncapitalizes every character from the current cursor position to the end of the word ALT+C # capitalizes the letter under the cursor. The cursor then moves to the end of the word. ALT+R # reverts any changes to a command you've pulled from your history if you've edited it. ALT+? # list possible completions to what is typed ALT+^ # expand line to most recent match from history
CTRL+X then ( # start recording a keyboard macro CTRL+X then ) # finish recording keyboard macro CTRL+X then E # recall last recorded keyboard macro CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands
BACKSPACE # deletes one character backward DELETE # deletes one character under cursor
history # shows command line history
!! # repeats the last command
!
exit # logs out of current session
BASH BASICS
env # displays all environment variables
echo $SHELL # displays the shell you're using echo $BASH_VERSION # displays bash version
bash # if you want to use bash (type exit to go back to your previously opened shell) whereis bash # locates the binary, source and manual-page for a command which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)
clear # clears content on window (hide displayed lines)
FILE COMMANDS
ls # lists your files in current directory, ls
DIRECTORY COMMANDS
mkdir
SSH, SYSTEM INFO & NETWORK COMMANDS
ssh user@host # connects to host as user
ssh -p
whoami # returns your username
passwd # lets you change your password
quota -v # shows what your disk quota is
date # shows the current date and time
cal # shows the month's calendar
uptime # shows current uptime
w # displays whois online
finger
ping
time
VARIABLES
varname=value # defines a variable
varname=value command # defines a variable to be in the environment of a particular subprocess
echo $varname # checks a variable's value
echo $$ # prints process ID of the current shell
echo $! # prints process ID of the most recently invoked background job
echo $? # displays the exit status of the last command
read
array[0]=valA # how to define an array array[1]=valB array[2]=valC array=([2]=valC [0]=valA [1]=valB) # another way array=(valA valB valC) # and another
${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed ${#array[i]} # to find out the length of any element in the array ${#array[@]} # to find out how many values there are in the array
declare -a # the variables are treated as arrays declare -f # uses function names only declare -F # displays function names without definitions declare -i # the variables are treated as integers declare -r # makes the variables read-only declare -x # marks the variables for export via the environment
${varname:-word} # if varname exists and isn't null, return its value; otherwise return word ${varname:word} # if varname exists and isn't null, return its value; otherwise return word ${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value ${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script ${varname:+word} # if varname exists and isn't null, return word; otherwise return null ${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest ${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest ${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest ${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest ${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced ${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced
${#varname} # returns the length of the value of the variable as a character string
*(patternlist) # matches zero or more occurrences of the given patterns +(patternlist) # matches one or more occurrences of the given patterns ?(patternlist) # matches zero or one occurrence of the given patterns @(patternlist) # matches exactly one of the given patterns !(patternlist) # matches anything except one of the given patterns
$(UNIX command) # command substitution: runs the command and returns standard output
FUNCTIONS
The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth
.
$@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters
.
function functname() { shell commands }
unset -f functname # deletes a function definition declare -f # displays all defined functions in your login session
FLOW CONTROLS
statement1 && statement2 # and operator statement1 || statement2 # or operator
-a # and operator inside a test conditional expression -o # or operator inside a test conditional expression
STRINGS
str1 == str2 # str1 matches str2 str1 != str2 # str1 does not match str2 str1 < str2 # str1 is less than str2 (alphabetically) str1 > str2 # str1 is greater than str2 (alphabetically) str1 > str2 # str1 is sorted after str2 str1 \< str2 # str1 is sorted before str2 -n str1 # str1 is not null (has length greater than 0) -z str1 # str1 is null (has length 0)
FILES
-a file # file exists or its compilation is successful -d file # file exists and is a directory -e file # file exists; same -a -f file # file exists and is a regular file (i.e., not a directory or other special type of file) -r file # you have read permission -s file # file exists and is not empty -w file # your have write permission -x file # you have execute permission on file, or directory search permission if it is a directory -N file # file was modified since it was last read -O file # you own file -G file # file's group ID matches yours (or one of yours, if you are in multiple groups) file1 -nt file2 # file1 is newer than file2 file1 -ot file2 # file1 is older than file2
NUMBERS
-lt # less than -le # less than or equal -eq # equal -ge # greater than or equal -gt # greater than -ne # not equal
if condition then statements [elif condition then statements...] [else statements] fi
for x in {1..10} do statements done
for name [in list] do statements that can use $name done
for (( initialisation ; ending condition ; update )) do statements... done
case expression in pattern1 ) statements ;; pattern2 ) statements ;; esac
select name [in list] do statements that can use $name done
while condition; do statements done
until condition; do statements done
COMMAND-LINE PROCESSING CYCLE
The default order for command lookup is functions, followed by built-ins, with scripts and executables last
.
There are three built-ins that you can use to override this order: `command`, `builtin` and `enable
`.
command # removes alias and function lookup. Only built-ins and commands found in the search path are executed builtin # looks up only built-in commands, ignoring functions and commands found in PATH enable # enables and disables shell built-ins
eval # takes arguments and run them through the command-line processing steps all over again
INPUT/OUTPUT REDIRECTORS
cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2 < file # takes standard input from file
file # directs standard output to file
file # directs standard output to file; append to file if it already exists |file # forces standard output to file even if noclobber is set n>|file # forces output to file from file descriptor n even if noclobber is set <> file # uses file as both standard input and standard output n<>file # uses file as both input and output for file descriptor n n>file # directs file descriptor n to file n
>file # directs file description n to file; append to file if it already exists n>& # duplicates standard output to file descriptor n n<& # duplicates standard input from file descriptor n n>&m # file descriptor n is made to be a copy of the output file descriptor n<&m # file descriptor n is made to be a copy of the input file descriptor &>file # directs standard output and standard error to file <&- # closes the standard input &- # closes the standard output n>&- # closes the ouput from file descriptor n n<&- # closes the input from file descripor n
|tee
PROCESS HANDLING
To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y
.
This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal
.
Of course, to interrupt a job, type CTRL+C
.
myCommand & # runs job in the background and prompts back the shell
jobs # lists all jobs (use with -l to see associated PID)
fg # brings a background job into the foreground fg %+ # brings most recently invoked background job fg %- # brings second most recently invoked background job fg %N # brings job number N fg %string # brings job whose command begins with string fg %?string # brings job whose command contains string
kill -l # returns a list of all signals on the system, by name and number kill PID # terminates process with specified PID kill -s SIGKILL 4500 # sends a signal to force or terminate the process kill -15 913 # Ending PID 913 process with signal 15 (TERM) kill %1 # Where %1 is the number of job as read from 'jobs' command.
ps # prints a line of information about the current running login shell and any processes running under it ps -a # selects all processes with a tty except session leaders
trap cmd sig1 sig2 # executes a command when a signal is received by the script trap "" sig1 sig2 # ignores that signals trap - sig1 sig2 # resets the action taken when the signal is received to the default
disown <PID|JID> # removes the process from the list of jobs
wait # waits until all background jobs have finished
sleep
pv # display progress bar for data handling commands. often used with pipe like |pv yes # give yes response everytime an input is requested from script/process
TIPS & TRICKS
set an alias
cd; nano .bash_profile
alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile
to quickly go to a specific directory
cd; nano .bashrc
shopt -s cdable_vars export websites="/Users/mac/Documents/websites"
source .bashrc cd $websites
DEBUGGING SHELL PROGRAMS
bash -n scriptname # don't run commands; check for syntax errors only set -o noexec # alternative (set option in script)
bash -v scriptname # echo commands before running them set -o verbose # alternative (set option in script)
bash -x scriptname # echo commands after command-line processing set -o xtrace # alternative (set option in script)
trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits
function errtrap { es=$? echo "ERROR line $1: Command exited with status $es." }
trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exits with non-zero status
function dbgtrap { echo "badvar is $badvar" }
trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script
...section of code in which the problem occurs
... trap - DEBUG # turn off the DEBUG trap
function returntrap { echo "A return occurred" }
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
COLORS AND BACKGROUNDS
note: \e or \x1B also work instead of \033
Reset
Color_Off='\033[0m' # Text Reset
Regular Colors
Black='\033[0;30m' # Black Red='\033[0;31m' # Red Green='\033[0;32m' # Green Yellow='\033[0;33m' # Yellow Blue='\033[0;34m' # Blue Purple='\033[0;35m' # Purple Cyan='\033[0;36m' # Cyan White='\033[0;97m' # White
Additional colors
LGrey='\033[0;37m' # Ligth Gray DGrey='\033[0;90m' # Dark Gray LRed='\033[0;91m' # Ligth Red LGreen='\033[0;92m' # Ligth Green LYellow='\033[0;93m'# Ligth Yellow LBlue='\033[0;94m' # Ligth Blue LPurple='\033[0;95m'# Light Purple LCyan='\033[0;96m' # Ligth Cyan
Bold
BBlack='\033[1;30m' # Black BRed='\033[1;31m' # Red BGreen='\033[1;32m' # Green BYellow='\033[1;33m'# Yellow BBlue='\033[1;34m' # Blue BPurple='\033[1;35m'# Purple BCyan='\033[1;36m' # Cyan BWhite='\033[1;37m' # White
Underline
UBlack='\033[4;30m' # Black URed='\033[4;31m' # Red UGreen='\033[4;32m' # Green UYellow='\033[4;33m'# Yellow UBlue='\033[4;34m' # Blue UPurple='\033[4;35m'# Purple UCyan='\033[4;36m' # Cyan UWhite='\033[4;37m' # White
Background
On_Black='\033[40m' # Black On_Red='\033[41m' # Red On_Green='\033[42m' # Green On_Yellow='\033[43m'# Yellow On_Blue='\033[44m' # Blue On_Purple='\033[45m'# Purple On_Cyan='\033[46m' # Cyan On_White='\033[47m' # White
Example of usage
echo -e "${Green}This is GREEN text${Color_Off} and normal text" echo -e "${Red}${On_White}This is Red test on White background${Color_Off}"
option -e is mandatory, it enable interpretation of backslash escapes
printf "${Red} This is red \n"
`
Find
To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG
)
find . -iname "*.jpg"
To find directories
find . -type d
To find files
find . -type f
To find files by octal permission
find . -type f -perm 777
To find files with setuid bit set
find . -xdev ( -perm -4000 ) -type f -print0 | xargs -0 ls -l
To find files with extension '.txt' and remove them
find ./path/ -name '*.txt' -exec rm '{}' \;
To find files with extension '.txt' and look for a string into them
find ./path/ -name '*.txt' | xargs grep 'string'
To find files with size bigger than 5 Mebibyte and sort them by size
find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z
To find files bigger than 2 Megabyte and list them
find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
To find files modified more than 7 days ago and list file information
find . -type f -mtime +7d -ls
To find symlinks owned by a user and list file information
find . -type l -user
To search for and delete empty directories
find . -type d -empty -exec rmdir {} \;
To search for directories named build at a max depth of 2 directories
find . -maxdepth 2 -name build -type d
To search all files who are not in .git directory
find . ! -iwholename '.git' -type f
To find all files that have the same node (hard link) as MY_FILE_HERE
find . -type f -samefile MY_FILE_HERE 2>/dev/null
To find all files in the current directory and modify their permissions
find . -type f -exec chmod 644 {} \;

Wiki Nav
- Home
- add copy to code blocks.md
- Add site search w algolia.md
- adding mailing list.md
- Adding search 2 gatsby site.md
- awesome.md
- broken links.md
- configure custom domain.md
- contentauthoring.md
- full text search w lunar.md
- inject 4.md
- inject3.md
- inject4.md
- injected content part2.md
- injected js part4.md
- injected part3.md
- links 2 embed.md
- links to remember
- Netlify Injected Content
- old version of index.md
- optimize vscode.md
- possibly useful snippets.md
- privacy policy.md
- random stuff.md
- random.md
- ref type
- SEO.md
- stable points.md
- tech used.md
- Technologies Used.md
- THINGS TO EMBED.md
- validation report.md
- web archive.md
- wordpress vs headless cms.md
Dependencies
Click to expand!
^ 4.10.3
4.10.5
4.10.5
4.10.5
0.0.4
^ 24.7.1
^ 0.1.11
^ 2.5.0
^ 3.0.0
^ 24.7.1
^ 4.17.11
^ 16.8.6
0.0.0
6.26.0
3.4.0
^ 13
~ 3.1.1
~ 3.0.2
^ 4.2
^ 3.3.0
^ 6.6.0
~ 2.1.2
~ 5.1.0
~ 2.1.0
~ 4.0.1
^ 7.0.0
~ 3.0.0
^ 15.0.0
~ 3.4.0
^ 3.0.0
^ 9.0.1
^ 3.3.0
^ 1.2.0
2.2.6
^ 1.0.0
^ 14.1.0
^ 2.1.0
^ 3.1.0
^ 13.2.5
7.12.3
Cloudfare-Backup ââ Search Website: search ââ Backup Repo Deploy ââ Github pages ââ Go To Site Wiki
Docs Structure
.
âââ ./About
â âââ ./About/index.md
â âââ ./About/introduction2bg.md
â âââ ./About/me.md
â âââ ./About/resume.md
âââ ./articles
â âââ ./articles/algo.md
â âââ ./articles/basic-web-dev.md
âââ ./faq
â âââ ./faq/Contact.md
â âââ ./faq/index.md
â âââ ./faq/other-sites.md
âââ ./index.md
âââ ./jupyter-notebooks.md
âââ ./links
â âââ ./links/Social.md
â âââ ./links/index.md
â âââ ./links/my-websites.md
âââ ./portfolio-web.md
âââ ./python.md
âââ ./quick-reference
â âââ ./quick-reference/Emmet.md
â âââ ./quick-reference/index.md
â âââ ./quick-reference/installation.md
â âââ ./quick-reference/new-repo-instructions.md
âââ ./react
â âââ ./react/createReactApp.md
â âââ ./react/index.md
â âââ ./react/react2.md
âââ ./resources.md
âââ ./tools
âââ ./tools/Git-Html-Preview.md
âââ ./tools/default-readme.md
âââ ./tools/index.md
âââ ./tools/notes-template.md
âââ ./tools/plug-ins.md
7 directories, 29 files
Sitemap
Sitemap
Links
Try it out without cloning the entire repo
stackblitz demo hosted on firebase
SITEMAP
đâhttps://bgoonz-blog.netlify.app/đșïž
đâblog/awesome-graphqlđșïž
đâblog/big-o-complexityđșïž
đâblog/blog-archiveđșïž
đâblog/blogwcommentsđșïž
đâblog/data-structuresđșïž
đâblog/flow-control-in-pythonđșïž
đâblog/functions-in-pythonđșïž
đâblog/git-gatewayđșïž
đâblog/interview-questions-jsđșïž
đâblog/media-queries-explainedđșïž
đâblog/netlify-cmsđșïž
đâblog/platform-docsđșïž
đâblog/python-for-js-devđșïž
đâblog/python-resourcesđșïž
đâblog/web-dev-trendsđșïž
đâblog/web-scrapingđșïž
đâdocs/other-contentđșïž
đâdocs/privacy-policyđșïž
đâdocs/quick-referenceđșïž
đâdocs/about/eng-portfoliođșïž
đâdocs/about/ideas-for-this-websiteđșïž
đâdocs/about/intrestsđșïž
đâdocs/about/interviewđșïž
đâdocs/about/resumeđșïž
đâdocs/articles/basic-web-devđșïž
đâdocs/articles/buffersđșïž
đâdocs/articles/dev-depđșïž
đâdocs/articles/event-loopđșïž
đâdocs/articles/fs-moduleđșïž
đâdocs/articles/how-the-web-worksđșïž
đâdocs/articles/httpđșïž
đâdocs/articles/installđșïž
đâdocs/articles/introđșïž
đâdocs/articles/media-queries-no-moređșïž
đâdocs/articles/module-exportsđșïž
đâdocs/articles/nextjsđșïž
đâdocs/articles/node-api-expressđșïž
đâdocs/articles/node-cli-argsđșïž
đâdocs/articles/node-common-modulesđșïž
đâdocs/articles/node-env-variablesđșïž
đâdocs/articles/node-js-languageđșïž
đâdocs/articles/node-package-managerđșïž
đâdocs/articles/node-replđșïž
đâdocs/articles/node-run-cliđșïž
đâdocs/articles/nodejsđșïž
đâdocs/articles/nodevsbrowserđșïž
đâdocs/articles/npmđșïž
đâdocs/articles/npxđșïž
đâdocs/articles/os-moduleđșïž
đâdocs/articles/package-lockđșïž
đâdocs/articles/reading-filesđșïž
đâdocs/articles/semanticđșïž
đâdocs/articles/semantic-htmlđșïž
đâdocs/articles/the-uniform-resource-locator-(url)đșïž>)
đâdocs/articles/understanding-firebaseđșïž
đâdocs/articles/v8đșïž
đâdocs/articles/web-standards-checklistđșïž
đâdocs/articles/webdev-toolsđșïž
đâdocs/articles/write-2-json-with-pythonđșïž
đâdocs/articles/writing-filesđșïž
đâdocs/audio/audiođșïž
đâdocs/audio/audio-feature-extractionđșïž
đâdocs/audio/discrete-fftđșïž
đâdocs/audio/dtw-python-explainedđșïž
đâdocs/audio/dynamic-time-warpingđșïž
đâdocs/audio/web-audio-apiđșïž
đâdocs/career/confidenceđșïž
đâdocs/career/dev-interviewđșïž
đâdocs/career/interview-dos-n-dontsđșïž
đâdocs/career/job-boardsđșïž
đâdocs/community/an-open-letter-2-future-developersđșïž
đâdocs/community/video-chatđșïž
đâdocs/content/algođșïž
đâdocs/content/archiveđșïž
đâdocs/content/data-structures-algođșïž
đâdocs/content/gatsby-Queries-Mutationsđșïž
đâdocs/content/history-apiđșïž
đâdocs/content/projectsđșïž
đâdocs/content/recent-projectsđșïž
đâdocs/content/trouble-shootingđșïž
đâdocs/docs/appendixđșïž
đâdocs/docs/contentđșïž
đâdocs/docs/data-structures-docsđșïž
đâdocs/docs/git-referenceđșïž
đâdocs/docs/git-reposđșïž
đâdocs/docs/html-specđșïž
đâdocs/docs/markdownđșïž
đâdocs/docs/no-whiteboardingđșïž
đâdocs/docs/node-docs-completeđșïž
đâdocs/docs/node-docs-fullđșïž
đâdocs/docs/regex-in-jsđșïž
đâdocs/docs/sitemapđșïž
đâdocs/faq/contactđșïž
đâdocs/faq/plug-insđșïž
đâdocs/interact/callstack-visualđșïž
đâdocs/interact/clockđșïž
đâdocs/interact/jupyter-notebooksđșïž
đâdocs/interact/other-sitesđșïž
đâdocs/interact/video-chatđșïž
đâdocs/javascript/arrow-functionsđșïž
đâdocs/javascript/await-keywordđșïž
đâdocs/javascript/bigođșïž
đâdocs/javascript/clean-codeđșïž
đâdocs/javascript/constructor-functionsđșïž
đâdocs/javascript/promisesđșïž
đâdocs/javascript/reviewđșïž
đâdocs/javascript/this-is-about-thisđșïž
đâdocs/projects/medium-linksđșïž
đâdocs/projects/my-websitesđșïž
đâdocs/python/at-lengthđșïž
đâdocs/python/basicsđșïž
đâdocs/python/cheat-sheetđșïž
đâdocs/python/comprehensive-guideđșïž
đâdocs/python/examplesđșïž
đâdocs/python/flow-controlđșïž
đâdocs/python/functionsđșïž
đâdocs/python/google-sheets-apiđșïž
đâdocs/python/intro-for-js-devsđșïž
đâdocs/python/python-dsđșïž
đâdocs/python/snippetsđșïž
đâdocs/quick-reference/Emmetđșïž
đâdocs/quick-reference/all-emojisđșïž
đâdocs/quick-reference/create-react-appđșïž
đâdocs/quick-reference/git-bashđșïž
đâdocs/quick-reference/git-tricksđșïž
đâdocs/quick-reference/google-firebaseđșïž
đâdocs/quick-reference/heroku-error-codesđșïž
đâdocs/quick-reference/installationđșïž
đâdocs/quick-reference/markdown-dropdownsđșïž
đâdocs/quick-reference/minifictionđșïž
đâdocs/quick-reference/new-repo-instructionsđșïž
đâdocs/quick-reference/psql-setupđșïž
đâdocs/quick-reference/pull-request-rubricđșïž
đâdocs/quick-reference/quick-linksđșïž
đâdocs/quick-reference/topReposđșïž
đâdocs/quick-reference/understanding-pathđșïž
đâdocs/quick-reference/vscode-themesđșïž
đâdocs/react/cheatsheetđșïž
đâdocs/react/createReactAppđșïž
đâdocs/react/react-docsđșïž
đâdocs/react/react-in-depthđșïž
đâdocs/react/react2đșïž
đâdocs/react/render-elementsđșïž
đâdocs/reference/awesome-listsđșïž
đâdocs/reference/awesome-staticđșïž
đâdocs/reference/bookmarksđșïž
đâdocs/reference/embed-the-webđșïž
đâdocs/reference/github-searchđșïž
đâdocs/reference/how-2-reinstall-npmđșïž
đâdocs/reference/how-to-kill-a-processđșïž
đâdocs/reference/installing-nodeđșïž
đâdocs/reference/intro-to-nodejsđșïž
đâdocs/reference/notes-templateđșïž
đâdocs/reference/psqlđșïž
đâdocs/reference/resourcesđșïž
đâdocs/reference/vscodeđșïž
đâdocs/reference/web-api'sđșïž
đâdocs/tools/data-structuresđșïž
đâdocs/tools/dev-utilitiesđșïž
đâdocs/tools/google-cloudđșïž
đâdocs/tools/markdown-htmlđșïž
đâdocs/tools/more-toolsđșïž
đâdocs/tutorials/google-lighthouse-cliđșïž
đ Quick start
Create a Gatsby site.
Use the Gatsby CLI to create a new site, specifying the default starter.
# create a new Gatsby site using the default starter
gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default
Start developing.
Navigate into your new site's directory and start it up.
cd my-default-starter/
gatsby develop
Open the source code and start editing!
Your site is now running at
http://localhost:8000!Note: You'll also see a second link:
http://localhost:8000/___graphql. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the Gatsby tutorial.Open the
my-default-starterdirectory in your code editor of choice and editsrc/pages/index.js. Save your changes and the browser will update in real time!
đ§ What's inside
?
A quick look at the top-level files and directories you'll see in a Gatsby project.
.
âââ node_modules
âââ src
âââ .gitignore
âââ .prettierrc
âââ gatsby-browser.js
âââ gatsby-config.js
âââ gatsby-node.js
âââ gatsby-ssr.js
âââ LICENSE
âââ package-lock.json
âââ package.json
âââ README.md
/node_modules: This directory contains all of the modules of code that your project depends on (npm packages) are automatically installed./src: This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser) such as your site header or a page template.srcis a convention for "source code"..gitignore: This file tells git which files it should not track / not maintain a version history for..prettierrc: This is a configuration file for Prettier. Prettier is a tool to help keep the formatting of your code consistent.gatsby-browser.js: This file is where Gatsby expects to find any usage of the Gatsby browser APIs (if any). These allow customization/extension of default Gatsby settings affecting the browser.gatsby-config.js: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. (Check out the config docs for more detail).gatsby-node.js: This file is where Gatsby expects to find any usage of the Gatsby Node APIs (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.gatsby-ssr.js: This file is where Gatsby expects to find any usage of the Gatsby server-side rendering APIs (if any). These allow customization of default Gatsby settings affecting server-side rendering.LICENSE: This Gatsby starter is licensed under the 0BSD license. This means that you can see this file as a placeholder and replace it with your own license.package-lock.json(Seepackage.jsonbelow, first). This is an automatically generated file based on the exact versions of your npm dependencies that were installed for your project. (You won't change this file directly).package.json: A manifest file for Node.js projects, which includes things like metadata (the project's name, author, etc). This manifest is how npm knows which packages to install for your project.README.md: A text file containing useful reference information about your project.
đ Learning Gatsby
Looking for more guidance? Full documentation for Gatsby lives on the website. Here are some places to start:
For most developers, we recommend starting with our in-depth tutorial for creating a site with Gatsby. It starts with zero assumptions about your level of ability and walks through every step of the process.
To dive straight into code samples, head to our documentation. In particular, check out the Guides, API Reference, and Advanced Tutorials sections in the sidebar.
đ« Deploy
Codebase
bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ tree -f
.
âââ ./components
â âââ ./components/ActionLink.js
â âââ ./components/CtaButtons.js
â âââ ./components/DocsMenu.js
â âââ ./components/DocsSubmenu.js
â âââ ./components/Footer.js
â âââ ./components/Header.js
â âââ ./components/Icon.js
â âââ ./components/Layout.js
â âââ ./components/SectionContent.js
â âââ ./components/SectionCta.js
â âââ ./components/SectionDocs.js
â âââ ./components/SectionGrid.js
â âââ ./components/SectionHero.js
â âââ ./components/Submenu.js
â âââ ./components/global.css
â âââ ./components/index.js
âââ ./data
â âââ ./data/doc_sections.yml
âââ ./hooks
â âââ ./hooks/useScript.js
âââ ./html.js
âââ ./pages
â âââ ./pages/blog
â â âââ ./pages/blog/blog-archive.md
â â âââ ./pages/blog/blogwcomments.md
â â âââ ./pages/blog/data-structures.md
â â âââ ./pages/blog/index.md
â â âââ ./pages/blog/my-medium.md
â â âââ ./pages/blog/platform-docs.md
â â âââ ./pages/blog/python-for-js-dev.md
â â âââ ./pages/blog/python-resources.md
â â âââ ./pages/blog/web-scraping.md
â âââ ./pages/docs
â â âââ ./pages/docs/about
â â â âââ ./pages/docs/about/index.md
â â â âââ ./pages/docs/about/me.md
â â â âââ ./pages/docs/about/node
â â â â âââ ./pages/docs/about/node/install.md
â â â â âââ ./pages/docs/about/node/intro.md
â â â â âââ ./pages/docs/about/node/nodejs.md
â â â â âââ ./pages/docs/about/node/nodevsbrowser.md
â â â â âââ ./pages/docs/about/node/reading-files.md
â â â â âââ ./pages/docs/about/node/writing-files.md
â â â âââ ./pages/docs/about/npm.md
â â â âââ ./pages/docs/about/resume.md
â â âââ ./pages/docs/articles
â â â âââ ./pages/docs/articles/algo.md
â â â âââ ./pages/docs/articles/article-compilation.md
â â â âââ ./pages/docs/articles/basic-web-dev.md
â â â âââ ./pages/docs/articles/gists.md
â â â âââ ./pages/docs/articles/index.md
â â â âââ ./pages/docs/articles/install.md
â â â âââ ./pages/docs/articles/intro.md
â â â âââ ./pages/docs/articles/python.md
â â â âââ ./pages/docs/articles/reading-files.md
â â â âââ ./pages/docs/articles/resources.md
â â â âââ ./pages/docs/articles/ten-jamstack-apis-to-checkout.md
â â â âââ ./pages/docs/articles/writing-files.md
â â âââ ./pages/docs/docs
â â â âââ ./pages/docs/docs/tools
â â â âââ ./pages/docs/docs/tools/file-types.md
â â âââ ./pages/docs/faq
â â â âââ ./pages/docs/faq/contact.md
â â â âââ ./pages/docs/faq/index.md
â â âââ ./pages/docs/gists.md
â â âââ ./pages/docs/index.md
â â âââ ./pages/docs/interact
â â â âââ ./pages/docs/interact/clock.md
â â â âââ ./pages/docs/interact/index.md
â â â âââ ./pages/docs/interact/jupyter-notebooks.md
â â âââ ./pages/docs/links
â â â âââ ./pages/docs/links/index.md
â â â âââ ./pages/docs/links/medium-links.md
â â â âââ ./pages/docs/links/my-websites.md
â â â âââ ./pages/docs/links/social.md
â â âââ ./pages/docs/quick-reference
â â â âââ ./pages/docs/quick-reference/Emmet.md
â â â âââ ./pages/docs/quick-reference/docs.md
â â â âââ ./pages/docs/quick-reference/index.md
â â â âââ ./pages/docs/quick-reference/installation.md
â â â âââ ./pages/docs/quick-reference/new-repo-instructions.md
â â âââ ./pages/docs/react
â â â âââ ./pages/docs/react/createReactApp.md
â â â âââ ./pages/docs/react/index.md
â â â âââ ./pages/docs/react/react2.md
â â âââ ./pages/docs/react-in-depth.md
â â âââ ./pages/docs/sitemap.md
â â âââ ./pages/docs/tools
â â âââ ./pages/docs/tools/index.md
â â âââ ./pages/docs/tools/notes-template.md
â â âââ ./pages/docs/tools/plug-ins.md
â â âââ ./pages/docs/tools/vscode.md
â âââ ./pages/index.md
â âââ ./pages/notes-template.md
â âââ ./pages/review.md
â âââ ./pages/showcase.md
âââ ./sass
â âââ ./sass/imports
â â âââ ./sass/imports/_animations.scss
â â âââ ./sass/imports/_buttons.scss
â â âââ ./sass/imports/_docs.scss
â â âââ ./sass/imports/_footer.scss
â â âââ ./sass/imports/_forms.scss
â â âââ ./sass/imports/_functions.scss
â â âââ ./sass/imports/_general.scss
â â âââ ./sass/imports/_header.scss
â â âââ ./sass/imports/_helpers.scss
â â âââ ./sass/imports/_icons.scss
â â âââ ./sass/imports/_palettes.scss
â â âââ ./sass/imports/_posts.scss
â â âââ ./sass/imports/_prism.scss
â â âââ ./sass/imports/_reset.scss
â â âââ ./sass/imports/_sections.scss
â â âââ ./sass/imports/_structure.scss
â â âââ ./sass/imports/_tables.scss
â â âââ ./sass/imports/_variables.scss
â âââ ./sass/main.scss
âââ ./templates
â âââ ./templates/advanced.js
â âââ ./templates/blog.js
â âââ ./templates/docs.js
â âââ ./templates/page.js
â âââ ./templates/post.js
âââ ./utils
âââ ./utils/attribute.js
âââ ./utils/classNames.js
âââ ./utils/cycler.js
âââ ./utils/getData.js
âââ ./utils/getPage.js
âââ ./utils/getPageByFilePath.js
âââ ./utils/getPages.js
âââ ./utils/htmlToReact.js
âââ ./utils/index.js
âââ ./utils/link.js
âââ ./utils/markdownify.js
âââ ./utils/pathJoin.js
âââ ./utils/toStyleObj.js
âââ ./utils/toUrl.js
âââ ./utils/withPrefix.js
21 directories, 119 files
bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$
Components
Click to see React Components (src folder)!
ActionLink!
Prerequisites
- A GitHub account
- The Gatsby CLI installed
Set up a Netlify CMS-managed Gatsby site in 5 steps
Step 1
Open your Terminal and run the following command from the Gatsby CLI to create a new Gatsby site using gatsby-personal-starter-blog.
gatsby new [your-project-name] https://github.com/thomaswangio/gatsby-personal-starter-blog
Step 2
Once the Gatsby site is finished installing all the packages and dependencies, you can now go into the directory and run the site locally.
cd [your-project-name]
gatsby develop
Now you can go to http://localhost:8000 to see your new site, but what's extra cool is that Netlify CMS is pre-installed and you can access it at http://localhost:8000/admin
A CMS, or content management system, is useful because you can add content like blog posts from a dashboard on your site, instead of having to add posts manually with Markdown. However, you'll likely want to be able to access the CMS from a deployed website, not just locally. For that, you'll need to deploy to Netlify through GitHub, set up continuous deployment, and do a few configurations. You'll go over this in Step-5.
Step 3
Open the project in your code editor and open static/admin/config.yml. Replace your-username/your-repo-name with your GitHub username and project name. This step is important for managing and deploying the Netlify CMS interface.
backend:
- name: test-repo
+ name: github
+ repo: your-username/your-repo-name
Customizing your site
Head into gatsby-config.js and you can edit your siteMetadata, add a Google Analytics tracking ID, and your app icon/favicon. Test out the edits for the deployed build by quitting the development server and running gatsby build && gatsby serve.
You'll likely also want to edit the README.md and package.json files to include your own project details.
Step 4
Open github.com and create a new repository, with the same name as your project. Push your new Gatsby site's code to GitHub using the following Terminal commands:
git init
git add .
git commit -m "initial commit"
git remote add origin https://github.com/[your-username]/[your-repo-name].git
git push -u origin master
Then, open app.netlify.com and add a "New site from Git". Choose your newly created repo and click on "Deploy site" with the default deployment settings.
Note: if you don't see the correct repo listed, you may need to install or reconfigure the Netlify app on GitHub.

Step 5
To make sure that Netlify CMS has access to your GitHub repo, you need to set up an OAuth application on GitHub. The instructions for that are here: Netlify's Using an Authorization Provider.
For the "Homepage URL" â you can use your Netlify subdomain, [name-of-your-site].netlify.com, or you can use a custom domain. To customize the subdomain, look for the "Edit site name" field under "Domain Management" for your project on the Netlify app. To connect your Netlify site to your custom domain instead, see Netlifyâs instructions on custom domains.
Once you've configured an authentication provider then you'll be able to use Netlify CMS at your deployed site to add new posts.

Copy the credentials of your new app listed on GitHub OAuth Apps and install a new auth provider on Netlify using them.

Benefits of Netlify CMS, GitHub, and Netlify Workflow
Congrats! Now that Netlify CMS is successfully configured to your project, every time you add a new post, the content will be stored in your repository and versioned on GitHub because Netlify CMS is Git-based. Also, thanks to Netlify's Continuous Deployment, a new version will be deployed every time you add or edit a post.
You can learn more about Netlify CMS and how to configure it further in the Netlify CMS documentation
Gatsby Project Structure | Gatsby
Excerpt
Inside a Gatsby project, you may see some or all of the following folders and files: Folders /.cache Automatically generated. This folderâŠ
Inside a Gatsby project, you may see some or all of the following folders and files:
/|
-- /.cache
|-- /plugins
|-- /public
|-- /src
|-- /api
|-- /pages
|-- /templates
|-- html.js
|-- /static
|-- gatsby-config.js
|-- gatsby-node.js
|-- gatsby-ssr.js
|-- gatsby-browser.js
/.cacheAutomatically generated. This folder is an internal cache created automatically by Gatsby. The files inside this folder are not meant for modification. Should be added to the.gitignorefile if not added already./pluginsThis folder hosts any project-specific ("local") plugins that aren't published as annpmpackage. Check out the plugin docs for more detail./publicAutomatically generated. The output of the build process will be exposed inside this folder. Should be added to the.gitignorefile if not added already./srcThis directory will contain all of the code related to what you will see on the frontend of your site (what you see in the browser), like your site header, or a page template. "src" is a convention for "source code"./apiJavaScript and TypeScript files undersrc/apibecome functions automatically with paths based on their file name. Check out the functions guide for more detail./pagesComponents undersrc/pagesbecome pages automatically with paths based on their file name. Check out the pages recipes for more detail./templatesContains templates for programmatically creating pages. Check out the templates docs for more detail.html.jsFor custom configuration of default.cache/default_html.js. Check out the custom HTML docs for more detail.
/staticIf you put a file into the static folder, it will not be processed by webpack. Instead it will be copied into the public folder untouched. Check out the assets docs for more detail.
gatsby-browser.js: This file is where Gatsby expects to find any usage of the Gatsby browser APIs (if any). These allow customization/extension of default Gatsby settings affecting the browser.gatsby-config.js: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. Check out the config docs for more detail.gatsby-node.js: This file is where Gatsby expects to find any usage of the Gatsby node APIs (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.gatsby-ssr.js: This file is where Gatsby expects to find any usage of the Gatsby server-side rendering APIs (if any). These allow customization of default Gatsby settings affecting server-side rendering.
The file/folder structure described above reflects Gatsby-specific files and folders. Since Gatsby sites are also React apps, it's common to use standard React code organization patterns such as folders like /components and /utils inside /src. The React docs have more information on a typical React app folder structure.
Layout Components | Gatsby
Excerpt
In this guide, you'll learn Gatsby's approach to layouts, how to create and use layout components, and how to prevent layout components fromâŠ
In this guide, you'll learn Gatsby's approach to layouts, how to create and use layout components, and how to prevent layout components from unmounting.
Gatsby does not, by default, automatically apply layouts to pages (there are, however, ways to do so which will be covered in a later section). Instead, Gatsby follows React's compositional model of importing and using components. This makes it possible to create multiple levels of layouts, e.g. a global header and footer, and then on some pages, a sidebar menu. It also makes it possible to pass data between layout and page components.
Layout components are for sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and/or navigation menu. On this page for example, the header at the top is part of gatsbyjs.com's layout component.
How to create layout components
It is recommended to create your layout components alongside the rest of your components (e.g. into src/components/).
Here is an example of a very basic layout component at src/components/layout.js:
import React from "react"export default function Layout({ children }) { return ( <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}> {children} </div> )}
How to import and add layout components to pages
If you want to apply a layout to a page, you will need to include the Layout component and wrap your page in it. For example, here is how you would apply your layout to the front page:
import React from "react"import Layout from "../components/layout"export default function Home() { return ( <Layout> <h1> I'm in a layout!</h1> </Layout> );}
Repeat for every page and template that needs this layout.
How to prevent layout components from unmounting
As mentioned earlier, Gatsby does not, by default, automatically wrap pages in a layout component. The "top level" component is the page itself. As a result, when the "top level" component changes between pages, React will re-render all children. This means that shared components like navigations will unmount and remount. This will break CSS transitions or React state within those shared components.
If you need to set a wrapper component around page components that won't get unmounted on page changes, use the wrapPageElement browser API and the SSR equivalent.
Alternatively, you can prevent your layout component from unmounting by using gatsby-plugin-layout, which implements the wrapPageElement APIs for you.
Adding Markdown Pages | Gatsby
Excerpt
Gatsby can use Markdown files to create pages in your site. You add plugins to read and understand folders with Markdown files and from themâŠ
Gatsby can use Markdown files to create pages in your site. You add plugins to read and understand folders with Markdown files and from them create pages automatically.
Here are the steps Gatsby follows for making this happen.
- Read files into Gatsby from the filesystem
- Transform Markdown to HTML and frontmatter to data
- Add a Markdown file
- Create a Collection Route component for the Markdown files
Read files into Gatsby from the filesystem
Use the plugin gatsby-source-filesystem to read files.
npm install gatsby-source-filesystem
Add PluginAdd plugin
Open gatsby-config.js to add the gatsby-source-filesystem plugin. The path option is how you set the directory to search for files.
module.exports = { siteMetadata: {
title: "My Gatsby Site", },
plugins: [ {
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: `${__dirname}/src/markdown-pages`,
},
},
],}
Completing the above step means that you've "sourced" the Markdown files from the filesystem. You can now "transform" the Markdown to HTML and the YAML frontmatter to JSON.
Transform Markdown to HTML and frontmatter to data using gatsby-transformer-remark
You'll use the plugin gatsby-transformer-remark to recognize files which are Markdown and read their content. The plugin will convert the frontmatter metadata part of your Markdown files as frontmatter and the content part as HTML.
npm install gatsby-transformer-remark
Add this to gatsby-config.js after the previously added gatsby-source-filesystem.
module.exports = { siteMetadata: {
title: "My Gatsby Site", },
plugins: [ {
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: `${__dirname}/src/markdown-pages`,
},
},
`gatsby-transformer-remark`, ],
}
Create a folder in the /src directory of your Gatsby application called markdown-pages. Now create a Markdown file inside it with the name post-1.md.
Frontmatter for metadata in Markdown files
When you create a Markdown file, you can include a set of key/value pairs that can be used to provide additional data relevant to specific pages in the GraphQL data layer. This data is called "frontmatter" and is denoted by the triple dashes at the start and end of the block. This block will be parsed by gatsby-transformer-remark as YAML. You can then query the data through the GraphQL API from your React components.
src/markdown-pages/post-1.md
---slug: "/blog/my-first-post"date: "2019-05-04"title: "My first blog post"---
What is important in this step is the key pair slug. The value that is assigned to the key slug is used in order to navigate to your post.
Create a Collection Route for the Markdown files
Create src/pages/{MarkdownRemark.frontmatter__slug}.js and add the following code:
src/pages/{MarkdownRemark.frontmatter__slug}.js
import React from "react"
import { graphql } from "gatsby"export default function Template({ data, }) { const { markdownRemark } = data const { frontmatter, html } = markdownRemark return ( <div className="blog-post-container"> <div className="blog-post"> <h1> {frontmatter.title}</h1> <h2> {frontmatter.date}</h2> <div className="blog-post-content" dangerouslySetInnerHTML={{ __html: html }} /> </div> </div> )}export const pageQuery = graphql` query($id: String!) { markdownRemark(id: {
eq: $id }) { html frontmatter { date(formatString: "MMMM DD, YYYY") slug title } } }`
Two things are important in the file above:
A GraphQL query is made in the second half of the file to get the Markdown data. Gatsby has automagically given you all the Markdown metadata and HTML in this query's result.
Note: To learn more about GraphQL, consider this excellent resource
The result of the query is injected by Gatsby into the component as the
dataprop.props.data.markdownRemarkis the property that has all the details of the Markdown file.
Next you could create a page component at src/pages/blog/index.js to serve as a listing page for all your blog posts.
This should get you started on some basic Markdown functionality in your Gatsby site. You can further customize the frontmatter and the component file to get desired effects!
For more information, have a look in the working example using-markdown-pages. You can find it in the Gatsby examples section.
Overview
The _.get() method in Lodash retrieves the objectâs value at a specific path.
If the value is not present at the objectâs specific path, it will be resolved as undefined. This method will return the default value if specified in such a case.
Syntax
_.get(object, path, defaultValue)
Parameters
This method accepts the following parameters:
object: The object in which the given path will be queried.path: The path used to retrieve the value from the object.defaultValue: The default value that will be returned for resolved values that are undefined.
Return value
This method will return the value at the specified path if found. Otherwise, it will return the default value if specified.
Example
Letâs look at an example of the _.get() method in the code snippet below:
Explanation
In the HTML tab:
- Line 5: We import the
lodashscript.
In the JavaScript tab:
Lines 2 to 15: We create an object to perform a query.
Line 18: We define a variable
collegeYopPathto get the value.Lines 19: We use the
_.get()method and pass theobject,collegeYopPath, and a default value as parameters.Line 22: We define a variable
falsyPathto get the value.Lines 23: We use the
_.get()method and pass theobject,falsyPathand adefault valueas parameters.
Output
- The
_.get()method at line 19 contains a valid path, and therefore the expression is resolved, and2021is printed on the console. - The
_.get()method at Line 23 contains an invalid path, and therefore the expression is resolved asundefined.
Technoloy

SOURCECODE
Overview
The _.get() method in Lodash retrieves the objectâs value at a specific path.
If the value is not present at the objectâs specific path, it will be resolved as undefined. This method will return the default value if specified in such a case.
Syntax
_.get(object, path, defaultValue)
Parameters
This method accepts the following parameters:
object: The object in which the given path will be queried.path: The path used to retrieve the value from the object.defaultValue: The default value that will be returned for resolved values that are undefined.
Return value
This method will return the value at the specified path if found. Otherwise, it will return the default value if specified.
Example
Letâs look at an example of the _.get() method in the code snippet below:
Explanation
In the HTML tab:
- Line 5: We import the
lodashscript.
In the JavaScript tab:
Lines 2 to 15: We create an object to perform a query.
Line 18: We define a variable
collegeYopPathto get the value.Lines 19: We use the
_.get()method and pass theobject,collegeYopPath, and a default value as parameters.Line 22: We define a variable
falsyPathto get the value.Lines 23: We use the
_.get()method and pass theobject,falsyPathand adefault valueas parameters.
Output
- The
_.get()method at line 19 contains a valid path, and therefore the expression is resolved, and2021is printed on the console. - The
_.get()method at Line 23 contains an invalid path, and therefore the expression is resolved asundefined.
bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ tree -f
.
âââ ./components
â âââ ./components/ActionLink.js
â âââ ./components/CtaButtons.js
â âââ ./components/DocsMenu.js
â âââ ./components/DocsSubmenu.js
â âââ ./components/Footer.js
â âââ ./components/Header.js
â âââ ./components/Icon.js
â âââ ./components/Layout.js
â âââ ./components/SectionContent.js
â âââ ./components/SectionCta.js
â âââ ./components/SectionDocs.js
â âââ ./components/SectionGrid.js
â âââ ./components/SectionHero.js
â âââ ./components/Submenu.js
â âââ ./components/global.css
â âââ ./components/index.js
âââ ./data
â âââ ./data/doc_sections.yml
âââ ./hooks
â âââ ./hooks/useScript.js
âââ ./html.js
âââ ./pages
â âââ ./pages/blog
â â âââ ./pages/blog/blog-archive.md
â â âââ ./pages/blog/blogwcomments.md
â â âââ ./pages/blog/data-structures.md
â â âââ ./pages/blog/index.md
â â âââ ./pages/blog/my-medium.md
â â âââ ./pages/blog/platform-docs.md
â â âââ ./pages/blog/python-for-js-dev.md
â â âââ ./pages/blog/python-resources.md
â â âââ ./pages/blog/web-scraping.md
â âââ ./pages/docs
â â âââ ./pages/docs/about
â â â âââ ./pages/docs/about/index.md
â â â âââ ./pages/docs/about/me.md
â â â âââ ./pages/docs/about/node
â â â â âââ ./pages/docs/about/node/install.md
â â â â âââ ./pages/docs/about/node/intro.md
â â â â âââ ./pages/docs/about/node/nodejs.md
â â â â âââ ./pages/docs/about/node/nodevsbrowser.md
â â â â âââ ./pages/docs/about/node/reading-files.md
â â â â âââ ./pages/docs/about/node/writing-files.md
â â â âââ ./pages/docs/about/npm.md
â â â âââ ./pages/docs/about/resume.md
â â âââ ./pages/docs/articles
â â â âââ ./pages/docs/articles/algo.md
â â â âââ ./pages/docs/articles/article-compilation.md
â â â âââ ./pages/docs/articles/basic-web-dev.md
â â â âââ ./pages/docs/articles/gists.md
â â â âââ ./pages/docs/articles/index.md
â â â âââ ./pages/docs/articles/install.md
â â â âââ ./pages/docs/articles/intro.md
â â â âââ ./pages/docs/articles/python.md
â â â âââ ./pages/docs/articles/reading-files.md
â â â âââ ./pages/docs/articles/resources.md
â â â âââ ./pages/docs/articles/ten-jamstack-apis-to-checkout.md
â â â âââ ./pages/docs/articles/writing-files.md
â â âââ ./pages/docs/docs
â â â âââ ./pages/docs/docs/tools
â â â âââ ./pages/docs/docs/tools/file-types.md
â â âââ ./pages/docs/faq
â â â âââ ./pages/docs/faq/contact.md
â â â âââ ./pages/docs/faq/index.md
â â âââ ./pages/docs/gists.md
â â âââ ./pages/docs/index.md
â â âââ ./pages/docs/interact
â â â âââ ./pages/docs/interact/clock.md
â â â âââ ./pages/docs/interact/index.md
â â â âââ ./pages/docs/interact/jupyter-notebooks.md
â â âââ ./pages/docs/links
â â â âââ ./pages/docs/links/index.md
â â â âââ ./pages/docs/links/medium-links.md
â â â âââ ./pages/docs/links/my-websites.md
â â â âââ ./pages/docs/links/social.md
â â âââ ./pages/docs/quick-reference
â â â âââ ./pages/docs/quick-reference/Emmet.md
â â â âââ ./pages/docs/quick-reference/docs.md
â â â âââ ./pages/docs/quick-reference/index.md
â â â âââ ./pages/docs/quick-reference/installation.md
â â â âââ ./pages/docs/quick-reference/new-repo-instructions.md
â â âââ ./pages/docs/react
â â â âââ ./pages/docs/react/createReactApp.md
â â â âââ ./pages/docs/react/index.md
â â â âââ ./pages/docs/react/react2.md
â â âââ ./pages/docs/react-in-depth.md
â â âââ ./pages/docs/sitemap.md
â â âââ ./pages/docs/tools
â â âââ ./pages/docs/tools/index.md
â â âââ ./pages/docs/tools/notes-template.md
â â âââ ./pages/docs/tools/plug-ins.md
â â âââ ./pages/docs/tools/vscode.md
â âââ ./pages/index.md
â âââ ./pages/notes-template.md
â âââ ./pages/review.md
â âââ ./pages/showcase.md
âââ ./sass
â âââ ./sass/imports
â â âââ ./sass/imports/_animations.scss
â â âââ ./sass/imports/_buttons.scss
â â âââ ./sass/imports/_docs.scss
â â âââ ./sass/imports/_footer.scss
â â âââ ./sass/imports/_forms.scss
â â âââ ./sass/imports/_functions.scss
â â âââ ./sass/imports/_general.scss
â â âââ ./sass/imports/_header.scss
â â âââ ./sass/imports/_helpers.scss
â â âââ ./sass/imports/_icons.scss
â â âââ ./sass/imports/_palettes.scss
â â âââ ./sass/imports/_posts.scss
â â âââ ./sass/imports/_prism.scss
â â âââ ./sass/imports/_reset.scss
â â âââ ./sass/imports/_sections.scss
â â âââ ./sass/imports/_structure.scss
â â âââ ./sass/imports/_tables.scss
â â âââ ./sass/imports/_variables.scss
â âââ ./sass/main.scss
âââ ./templates
â âââ ./templates/advanced.js
â âââ ./templates/blog.js
â âââ ./templates/docs.js
â âââ ./templates/page.js
â âââ ./templates/post.js
âââ ./utils
âââ ./utils/attribute.js
âââ ./utils/classNames.js
âââ ./utils/cycler.js
âââ ./utils/getData.js
âââ ./utils/getPage.js
âââ ./utils/getPageByFilePath.js
âââ ./utils/getPages.js
âââ ./utils/htmlToReact.js
âââ ./utils/index.js
âââ ./utils/link.js
âââ ./utils/markdownify.js
âââ ./utils/pathJoin.js
âââ ./utils/toStyleObj.js
âââ ./utils/toUrl.js
âââ ./utils/withPrefix.js
21 directories, 119 files
bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$
Source Code
Folder Structure (src)
.
âââ Combined_____-_____Doc.md
âââ components
â âââ ActionLink.js
â âââ CtaButtons.js
â âââ DarkToggle
â â âââ index.js
â â âââ styles.js
â âââ DocsMenu.js
â âââ DocsSubmenu.js
â âââ Footer.js
â âââ Header.js
â âââ Icon.js
â âââ Layout.js
â âââ SectionContent.js
â âââ SectionCta.js
â âââ SectionDocs.js
â âââ SectionGrid.js
â âââ SectionHero.js
â âââ Submenu.js
â âââ global.css
â âââ index.js
âââ data
â âââ doc_sections.yml
âââ hooks
â âââ addScript.js
â âââ index.js
â âââ useDarkMode.js
â âââ useEventListener.js
â âââ useMediaQuery.js
â âââ useOnClickOutside.js
â âââ useQueryParam.js
â âââ useSize.js
â âââ useStorage.js
âââ html.js
âââ pages
â âââ blog
â â âââ 300-react-questions.md
â â âââ awesome-graphql.md
â â âââ big-o-complexity.md
â â âââ blog-archive.md
â â âââ blogwcomments.md
â â âââ data-structures.md
â â âââ flow-control-in-python.md
â â âââ functions-in-python.md
â â âââ git-gateway.md
â â âââ index.md
â â âââ interview-questions-js.md
â â âââ netlify-cms.md
â â âââ platform-docs.md
â â âââ python-for-js-dev.md
â â âââ python-resources.md
â â âââ web-dev-trends.md
â â âââ web-scraping.md
â âââ docs
â â âââ about
â â â âââ eng-portfolio.md
â â â âââ ideas-for-this-website.md
â â â âââ index.md
â â â âââ intrests.md
â â â âââ job-search.md
â â â âââ resume.md
â â âââ articles
â â â âââ basic-web-dev.md
â â â âââ buffers.md
â â â âââ dev-dep.md
â â â âââ event-loop.md
â â â âââ fs-module.md
â â â âââ how-the-web-works.md
â â â âââ http.md
â â â âââ index.md
â â â âââ install.md
â â â âââ intro.md
â â â âââ modules.md
â â â âââ nextjs.md
â â â âââ node-api-express.md
â â â âââ node-cli-args.md
â â â âââ node-common-modules.md
â â â âââ node-env-variables.md
â â â âââ node-js-language.md
â â â âââ node-package-manager.md
â â â âââ node-repl.md
â â â âââ node-run-cli.md
â â â âââ nodejs.md
â â â âââ nodevsbrowser.md
â â â âââ npm.md
â â â âââ npx.md
â â â âââ os-module.md
â â â âââ reading-files.md
â â â âââ semantic-html.md
â â â âââ semantic.md
â â â âââ the-uniform-resource-locator-(url).md
â â â âââ understanding-firebase.md
â â â âââ v8.md
â â â âââ web-standards-checklist.md
â â â âââ webdev-tools.md
â â â âââ writing-files.md
â â âââ audio
â â â âââ audio-feature-extraction.md
â â â âââ audio.md
â â â âââ dfft.md
â â â âââ discrete-fft.md
â â â âââ dtw-python-explained.md
â â â âââ dynamic-time-warping.md
â â â âââ index.md
â â â âââ web-audio-api.md
â â âââ career
â â â âââ dev-interview.md
â â â âââ index.md
â â â âââ interview-dos-n-donts.md
â â â âââ job-boards.md
â â âââ community
â â â âââ an-open-letter-2-future-developers.md
â â â âââ index.md
â â â âââ video-chat.md
â â âââ content
â â â âââ algo.md
â â â âââ archive.md
â â â âââ gatsby-Queries-Mutations.md
â â â âââ history-api.md
â â â âââ index.md
â â â âââ main-projects.md
â â â âââ trouble-shooting.md
â â âââ data-structures
â â â âââ index.md
â â âââ docs
â â â âââ appendix.md
â â â âââ art-of-command-line.md
â â â âââ bash.md
â â â âââ content.md
â â â âââ css.md
â â â âââ data-structures-docs.md
â â â âââ es-6-features.md
â â â âââ git-reference.md
â â â âââ git-repos.md
â â â âââ html-spec.md
â â â âââ index.md
â â â âââ markdown.md
â â â âââ no-whiteboarding.md
â â â âââ node-docs-complete.md
â â â âââ node-docs-full.md
â â â âââ regex-in-js.md
â â â âââ sitemap.md
â â âââ faq
â â â âââ contact.md
â â â âââ index.md
â â â âââ plug-ins.md
â â âââ gists.md
â â âââ index.md
â â âââ interact
â â â âââ callstack-visual.md
â â â âââ clock.md
â â â âââ index.md
â â â âââ jupyter-notebooks.md
â â â âââ other-sites.md
â â â âââ video-chat.md
â â âââ interview
â â â âââ index.md
â â â âââ job-search-nav.md
â â â âââ review-concepts.md
â â âââ javascript
â â â âââ arrow-functions.md
â â â âââ asyncjs.md
â â â âââ await-keyword.md
â â â âââ bigo.md
â â â âââ clean-code.md
â â â âââ constructor-functions.md
â â â âââ index.md
â â â âââ promises.md
â â â âââ review.md
â â â âââ this-is-about-this.md
â â âââ leetcode
â â â âââ index.md
â â âââ privacy-policy.md
â â âââ projects
â â â âââ embeded-websites.md
â â â âââ index.md
â â â âââ list-of-projects.md
â â â âââ mini-projects.md
â â â âââ my-websites.md
â â âââ python
â â â âââ at-length.md
â â â âââ cheat-sheet.md
â â â âââ comprehensive-guide.md
â â â âââ examples.md
â â â âââ flow-control.md
â â â âââ functions.md
â â â âââ google-sheets-api.md
â â â âââ index.md
â â â âââ intro-for-js-devs.md
â â â âââ python-ds.md
â â â âââ snippets.md
â â âââ quick-reference
â â â âââ Emmet.md
â â â âââ all-emojis.md
â â â âââ create-react-app.md
â â â âââ git-bash.md
â â â âââ git-tricks.md
â â â âââ google-firebase.md
â â â âââ heroku-error-codes.md
â â â âââ index.md
â â â âââ installation.md
â â â âââ markdown-dropdowns.md
â â â âââ minifiction.md
â â â âââ new-repo-instructions.md
â â â âââ psql-setup.md
â â â âââ pull-request-rubric.md
â â â âââ quick-links.md
â â â âââ topRepos.md
â â â âââ understanding-path.md
â â â âââ vscode-themes.md
â â âââ react
â â â âââ ajax-n-apis.md
â â â âââ cheatsheet.md
â â â âââ createReactApp.md
â â â âââ demo.md
â â â âââ dont-use-index-as-keys.md
â â â âââ index.md
â â â âââ jsx.md
â â â âââ react-docs.md
â â â âââ react-in-depth.md
â â â âââ react2.md
â â â âââ render-elements.md
â â âââ reference
â â â âââ awesome-lists.md
â â â âââ awesome-static.md
â â â âââ bash-commands.md
â â â âââ bookmarks.md
â â â âââ embed-the-web.md
â â â âââ github-search.md
â â â âââ google-cloud.md
â â â âââ how-2-reinstall-npm.md
â â â âââ how-to-kill-a-process.md
â â â âââ index.md
â â â âââ installing-node.md
â â â âââ intro-to-nodejs.md
â â â âââ notes-template.md
â â â âââ psql.md
â â â âââ resources.md
â â â âââ vscode.md
â â â âââ web-api's.md
â â âââ search.md
â â âââ sitemap.md
â â âââ tips
â â â âââ array-methods.md
â â â âââ index.md
â â â âââ insert-into-array.md
â â âââ tools
â â â âââ Archive.md
â â â âââ data-structures.md
â â â âââ dev-utilities.md
â â â âââ index.md
â â â âââ markdown-html.md
â â âââ tutorials
â â âââ enviorment-setup.md
â â âââ index.md
â âââ index.md
â âââ privacy-policy.md
â âââ readme.md
â âââ showcase.md
âââ sass
â âââ imports
â â âââ _animations.scss
â â âââ _buttons.scss
â â âââ _docs.scss
â â âââ _footer.scss
â â âââ _forms.scss
â â âââ _functions.scss
â â âââ _general.scss
â â âââ _header.scss
â â âââ _helpers.scss
â â âââ _icons.scss
â â âââ _palettes.scss
â â âââ _posts.scss
â â âââ _prism.scss
â â âââ _reset.scss
â â âââ _sections.scss
â â âââ _structure.scss
â â âââ _tables.scss
â â âââ _variables.scss
â âââ main.scss
âââ templates
â âââ advanced.js
â âââ blog.js
â âââ docs.js
â âââ page.js
â âââ post.js
â âââ templates.md
âââ utils
âââ attribute.js
âââ blm-badge.js
âââ classNames.js
âââ cycler.js
âââ getData.js
âââ getPage.js
âââ getPageByFilePath.js
âââ getPages.js
âââ htmlToReact.js
âââ index.js
âââ link.js
âââ markdownify.js
âââ pathJoin.js
âââ toStyleObj.js
âââ toUrl.js
âââ withPrefix.js
32 directories, 272 files
Component Structure
.
âââ ActionLink.js
âââ CtaButtons.js
âââ DarkToggle
â âââ index.js
â âââ styles.js
âââ DocsMenu.js
âââ DocsSubmenu.js
âââ Footer.js
âââ Header.js
âââ Icon.js
âââ Layout.js
âââ SectionContent.js
âââ SectionCta.js
âââ SectionDocs.js
âââ SectionGrid.js
âââ SectionHero.js
âââ Submenu.js
âââ global.css
âââ index.js
import React from 'react';
import _ from 'lodash';
import { Link, withPrefix, classNames } from '../utils';
import Icon from './Icon';
export default class ActionLink extends React.Component {
render() {
let action = _.get(this.props, 'action', null);
return (
<Link
to={withPrefix(_.get(action, 'url', null))}
{...(_.get(action, 'new_window', null) ? { target: '_blank' } : null)}
{...(_.get(action, 'new_window', null) || _.get(action, 'no_follow', null)
? {
rel: (_.get(action, 'new_window', null) ? 'noopener ' : '') + (_.get(action, 'no_follow', null) ? 'nofollow' : '')
}
: null)}
className={classNames({
button: _.get(action, 'style', null) !== 'link',
'button-secondary': _.get(action, 'style', null) === 'secondary',
'button-icon': _.get(action, 'style', null) === 'icon'
})}
>
{_.get(action, 'style', null) === 'icon' && _.get(action, 'icon_class', null) ? (
<React.Fragment>
<Icon {...this.props} icon={_.get(action, 'icon_class', null)} />
<span className="screen-reader-text"> {_.get(action, 'label', null)}</span>
</React.Fragment>
) : (
_.get(action, 'label', null)
)}
</Link>
);
}
}
Table of Contents
- [getPage][1]
- [Parameters][2]
- [getPageByFilePath][3]
- [Parameters][4]
- [getPages][5]
- [Parameters][6]
- [Examples][7]
getPage
Get the page at the provided urlPath.
Parameters
pages[Array][8] Array of page objects. All pages must have 'url' field.urlPath[string][9] The url path to find the page by
Returns [Object][10]
getPageByFilePath
Get the page at the provided filePath.
Parameters
pages[Array][8] Array of page objects. All pages must have 'url' field.filePath[string][9] The file path to find the page by
Returns [Object][10]
getPages
Get all the pages located under the provided urlPath, not including the
index page. I.e.: All pages having their URLs start with urlPath excluding
the page having its URL equal to urlPath.
Parameters
pagesArray Array of page objects. All pages must have 'url' field.urlPathstring The url path to filter pages by
Examples
pages => [
{url: '/'},
{url: '/about'},
{url: '/posts'},
{url: '/posts/hello'},
{url: '/posts/world'}
]
getPages(pages, /posts')
=> [
{url: '/posts/hello'},
{url: '/posts/world'}
]
Returns Array
import React from 'react';
import _ from 'lodash';
import { Link, withPrefix, classNames } from '../utils';
export default class CtaButtons extends React.Component {
render() {
let actions = _.get(this.props, 'actions', null);
return _.map(actions, (action, action_idx) => (
<Link
key={action_idx}
to={withPrefix(_.get(action, 'url', null))}
{...(_.get(action, 'new_window', null) ? { target: '_blank' } : null)}
{...(_.get(action, 'new_window', null) || _.get(action, 'no_follow', null)
? {
rel: (_.get(action, 'new_window', null) ? 'noopener ' : '') + (_.get(action, 'no_follow', null) ? 'nofollow' : '')
}
: null)}
className={classNames({
button: _.get(action, 'style', null) === 'primary' || _.get(action, 'style', null) === 'secondary',
'button-secondary': _.get(action, 'style', null) === 'secondary'
})}
>
{_.get(action, 'label', null)}
</Link>
));
}
}
import React from 'react';
import _ from 'lodash';
import { getPage, classNames, Link, withPrefix, pathJoin, getPages } from '../utils';
import DocsSubmenu from './DocsSubmenu';
export default class DocsMenu extends React.Component {
render() {
let site = _.get(this.props, 'site', null);
let page = _.get(this.props, 'page', null);
let root_docs_path = _.get(site, 'data.doc_sections.root_docs_path', null);
let root_page = getPage(this.props.pageContext.pages, root_docs_path);
return (
<nav id="docs-nav" className="docs-nav">
<div id="docs-nav-inside" className="docs-nav-inside sticky">
<button id="docs-nav-toggle" className="docs-nav-toggle">
Navigate Docs
<span className="icon-angle-right" aria-hidden="true" />
</button>
<div className="docs-nav-menu">
<ul id="docs-menu" className="docs-menu">
<li
className={classNames('docs-menu-item', {
current: _.get(page, 'url', null) === _.get(root_page, 'url', null)
})}
>
<Link to={withPrefix(_.get(root_page, 'url', null))}> {_.get(root_page, 'frontmatter.title', null)}</Link>
</li>
{_.map(_.get(site, 'data.doc_sections.sections', null), (section, section_idx) => {
let section_path = pathJoin(root_docs_path, section);
let section_page = getPage(this.props.pageContext.pages, section_path);
let child_pages = _.orderBy(getPages(this.props.pageContext.pages, section_path), 'frontmatter.weight');
let child_count = _.size(child_pages);
let has_children = child_count > 0 ? true : false;
let is_current_page = _.get(page, 'url', null) === _.get(section_page, 'url', null) ? true : false;
let is_active = _.get(page, 'url', null).startsWith(_.get(section_page, 'url', null));
return (
<React.Fragment key={section_idx + '.1'}>
<li
key={section_idx}
className={classNames('docs-menu-item', {
'has-children': has_children,
current: is_current_page,
active: is_active
})}
>
<Link to={withPrefix(_.get(section_page, 'url', null))}> {_.get(section_page, 'frontmatter.title', null)}</Link>
{has_children && (
<React.Fragment>
<button className="docs-submenu-toggle">
<span className="screen-reader-text"> Submenu</span>
<span className="icon-angle-right" aria-hidden="true" />
</button>
<DocsSubmenu {...this.props} child_pages={child_pages} page={page} site={site} />
</React.Fragment>
)}
</li>
</React.Fragment>
);
})}
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import _ from 'lodash';
import { classNames, Link, withPrefix } from '../utils';
export default class DocsSubmenu extends React.Component {
render() {
let child_pages = _.get(this.props, 'child_pages', null);
let page = _.get(this.props, 'page', null);
return (
<ul className="docs-submenu">
{_.map(child_pages, (child_page, child_page_idx) => (
<li
key={child_page_idx}
className={classNames('docs-menu-item', {
current: _.get(page, 'url', null) === _.get(child_page, 'url', null)
})}
>
<Link to={withPrefix(_.get(child_page, 'url', null))}> {_.get(child_page, 'frontmatter.title', null)}</Link>
</li>
))}
</ul>
);
}
}
import _ from 'lodash';
import React from 'react';
import { htmlToReact } from '../utils';
import ActionLink from './ActionLink';
import addScript from './../hooks/addScript';
const Script = (props) => {
importScript('./../hooks/addScript.js');
};
export default class Footer extends React.Component {
render() {
return (
<footer id="colophon" className="site-footer outer">
<div>
<center>
<br />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@algolia/algoliasearch-netlify-frontend@1/dist/algoliasearchNetlify.css" />
<br />
<table cellPadding={0} cellSpacing={0} border={0}>
<tbody>
<tr>
<td
style={{
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt'
}}
>
<center>
<table
width="95%"
cellPadding={0}
cellSpacing={0}
border={0}
style={{
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt'
}}
>
<tbody>
<tr>
<td
style={{
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt'
}}
align="left"
>
<a target="_blank" href="https://search.freefind.com/siteindex.html?si=14588965">
index
</a>
</td>
<td
style={{
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt'
}}
align="center"
>
<a target="_blank" href="https://search.freefind.com/find.html?si=14588965&m=0&p=0">
sitemap
</a>
</td>
<td
style={{
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt'
}}
align="right"
>
<a target="_blank" href="https://search.freefind.com/find.html?si=14588965&pid=a">
advanced
</a>
</td>
</tr>
</tbody>
</table>
</center>
<form
style={{
margin: '0px',
marginTop: '2px'
}}
action="https://search.freefind.com/find.html"
method="get"
acceptCharset="utf-8"
target="_self"
>
<input type="hidden" name="si" defaultValue={14588965} />
<input type="hidden" name="pid" defaultValue="r" />
<input type="hidden" name="n" defaultValue={0} />
<input type="hidden" name="_charset_" defaultValue />
<input type="hidden" name="bcd" defaultValue="Ă·" />
<input type="text" name="query" size={15} />
<input type="submit" defaultValue="search" />
</form>
</td>
</tr>
<tr>
<td
style={{
textAlign: 'center',
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '7.5pt',
paddingTop: '4px'
}}
>
<a
style={{
textDecoration: 'none',
color: 'transparent'
}}
href="https://www.freefind.com"
rel="nofollow"
>
search engine
</a>
<a
style={{
textDecoration: 'none',
color: 'transparent'
}}
href="https://www.freefind.com"
rel="nofollow"
>
by
<span style={{ color: 'transparent' }}> freefind</span>
</a>
{
<iframe
src="https://bgoonz.github.io/fb-and-twitter-api-embeds/"
frameborder="0"
id="social-embed"
width="100%!important"
>
{' '}
</iframe>
}
</td>
</tr>
</tbody>
</table>
<a href="//pdfcrowd.com/url_to_pdf/?" onclick="if(!this.p)href+='&url='+encodeURIComponent(location.href);this.p=1">
Save to PDF
</a>
</center>
</div>
<div className="inner">
<div id="search" className="inner">
{' '}
</div>
<div className="site-footer-inside">
<p className="site-info">
{_.get(this.props, 'pageContext.site.siteMetadata.footer.content', null) && (
<span className="copyright"> {htmlToReact(_.get(this.props, 'pageContext.site.siteMetadata.footer.content', null))}</span>
)}
{_.map(_.get(this.props, 'pageContext.site.siteMetadata.footer.links', null), (action, action_idx) => (
<ActionLink key={action_idx} {...this.props} action={action} />
))}{' '}
</p>
{_.get(this.props, 'pageContext.site.siteMetadata.footer.has_social', null) && (
<div className="social-links">
{_.map(_.get(this.props, 'pageContext.site.siteMetadata.footer.social_links', null), (action, action_idx) => (
<ActionLink key={action_idx} {...this.props} action={action} />
))}{' '}
</div>
)}{' '}
</div>
</div>
</footer>
);
}
}
import React from 'react';
import _ from 'lodash';
import { Link, withPrefix, classNames } from '../utils';
import ActionLink from './ActionLink';
import Submenu from './Submenu';
export default class Header extends React.Component {
render() {
return (
<header id="masthead" className="site-header outer">
{/* <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@algolia/algoliasearch-netlify-frontend@1/dist/algoliasearchNetlify.css" /> */}
<br />
<div className="inner">
<div className="site-header-inside">
<div className="site-branding">
{_.get(this.props, 'pageContext.site.siteMetadata.header.logo_img', null) ? (
<p className="site-logo">
<Link to={withPrefix(_.get(this.props, 'pageContext.site.siteMetadata.header.url', null) || '/')}>
<img
src={withPrefix(_.get(this.props, 'pageContext.site.siteMetadata.header.logo_img', null))}
alt={_.get(this.props, 'pageContext.site.siteMetadata.header.logo_img_alt', null)}
/>
</Link>
</p>
) : (
<p className="site-title">
{' '}
WebDevHub
<Link to={withPrefix(_.get(this.props, 'pageContext.site.siteMetadata.header.url', null) || '/')}>
{_.get(this.props, 'pageContext.site.siteMetadata.header.title', null)}
</Link>
</p>
)}
</div>
<div id="search" className="inner">
{' '}
</div>
{_.get(this.props, 'pageContext.site.siteMetadata.header.has_nav', null) && (
<React.Fragment>
<nav id="main-navigation" className="site-navigation" aria-label="Main Navigation">
<div className="site-nav-inside">
<button id="menu-close" className="menu-toggle">
<span className="screen-reader-text"> Open Menu</span>
<span className="icon-close" aria-hidden="true" />
</button>
<ul className="menu">
{_.map(_.get(this.props, 'pageContext.site.siteMetadata.header.nav_links', null), (action, action_idx) => {
let page_url = _.trim(_.get(this.props, 'pageContext.url', null), '/');
let action_url = _.trim(_.get(action, 'url', null), '/');
return (
<li
key={action_idx}
className={classNames('menu-item', {
'has-children': _.get(action, 'has_subnav', null) && _.get(action, 'subnav_links', null),
current: page_url === action_url,
'menu-button': _.get(action, 'style', null) !== 'link'
})}
>
<ActionLink {...this.props} action={action} />
{_.get(action, 'has_subnav', null) && _.get(action, 'subnav_links', null) && (
<React.Fragment>
<button className="submenu-toggle">
<span className="icon-angle-right" aria-hidden="true" />
<span className="screen-reader-text"> Sub-menu</span>
</button>
<Submenu
{...this.props}
submenu={_.get(action, 'subnav_links', null)}
menu_class={'submenu'}
page={this.props.pageContext}
/>
</React.Fragment>
)}
</li>
);
})}
</ul>
</div>
</nav>
<button id="menu-open" className="menu-toggle">
<span className="screen-reader-text"> Close Menu</span>
<span className="icon-menu" aria-hidden="true" />
</button>
</React.Fragment>
)}
</div>
</div>
<div>
<a className="github-corner" href="https://github.com/bgoonz/BGOONZ_BLOG_2.0" aria-label="View source on Github">
<svg
aria-hidden="true"
width={40}
height={40}
viewBox="0 0 250 250"
style={{
zIndex: 100000,
fill: 'black',
color: '#fff',
position: 'fixed',
top: '0px',
border: 0,
left: '0px',
transform: 'scale(-1.5, 1.5)'
}}
>
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"> </path>
<path
className="octo-arm"
d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
fill="currentColor"
style={{ transformOrigin: '130px 106px' }}
>
{' '}
</path>
<path
className="octo-body"
d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
fill="currentColor"
>
{' '}
</path>
</svg>
</a>
</div>
</header>
);
}
}
import React from 'react';
import _ from 'lodash';
export default class Icon extends React.Component {
render() {
let icon = _.get(this.props, 'icon', null);
return (
<svg className="icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
{icon === 'dev' ? (
<path d="M7.42 10.05c-.18-.16-.46-.23-.84-.23H6l.02 2.44.04 2.45.56-.02c.41 0 .63-.07.83-.26.24-.24.26-.36.26-2.2 0-1.91-.02-1.96-.29-2.18zM0 4.94v14.12h24V4.94H0zM8.56 15.3c-.44.58-1.06.77-2.53.77H4.71V8.53h1.4c1.67 0 2.16.18 2.6.9.27.43.29.6.32 2.57.05 2.23-.02 2.73-.47 3.3zm5.09-5.47h-2.47v1.77h1.52v1.28l-.72.04-.75.03v1.77l1.22.03 1.2.04v1.28h-1.6c-1.53 0-1.6-.01-1.87-.3l-.3-.28v-3.16c0-3.02.01-3.18.25-3.48.23-.31.25-.31 1.88-.31h1.64v1.3zm4.68 5.45c-.17.43-.64.79-1 .79-.18 0-.45-.15-.67-.39-.32-.32-.45-.63-.82-2.08l-.9-3.39-.45-1.67h.76c.4 0 .75.02.75.05 0 .06 1.16 4.54 1.26 4.83.04.15.32-.7.73-2.3l.66-2.52.74-.04c.4-.02.73 0 .73.04 0 .14-1.67 6.38-1.8 6.68z" />
) : icon === 'facebook' ? (
<path d="M23.998 12c0-6.628-5.372-12-11.999-12C5.372 0 0 5.372 0 12c0 5.988 4.388 10.952 10.124 11.852v-8.384H7.078v-3.469h3.046V9.356c0-3.008 1.792-4.669 4.532-4.669 1.313 0 2.686.234 2.686.234v2.953H15.83c-1.49 0-1.955.925-1.955 1.874V12h3.328l-.532 3.469h-2.796v8.384c5.736-.9 10.124-5.864 10.124-11.853z" />
) : icon === 'github' ? (
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
) : icon === 'instagram' ? (
<path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913a5.885 5.885 0 001.384 2.126A5.868 5.868 0 004.14 23.37c.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558a5.898 5.898 0 002.126-1.384 5.86 5.86 0 001.384-2.126c.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913a5.89 5.89 0 00-1.384-2.126A5.847 5.847 0 0019.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227a3.81 3.81 0 01-.899 1.382 3.744 3.744 0 01-1.38.896c-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421a3.716 3.716 0 01-1.379-.899 3.644 3.644 0 01-.9-1.38c-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678a6.162 6.162 0 100 12.324 6.162 6.162 0 100-12.324zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405a1.441 1.441 0 01-2.88 0 1.44 1.44 0 012.88 0z" />
) : icon === 'linkedin' ? (
<path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
) : icon === 'pinterest' ? (
<path d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z" />
) : icon === 'reddit' ? (
<path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z" />
) : icon === 'twitter' ? (
<path d="M23.954 4.569a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.691 8.094 4.066 6.13 1.64 3.161a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.061a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.937 4.937 0 004.604 3.417 9.868 9.868 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.054 0 13.999-7.496 13.999-13.986 0-.209 0-.42-.015-.63a9.936 9.936 0 002.46-2.548l-.047-.02z" />
) : icon === 'youtube' ? (
<path d="M23.495 6.205a3.007 3.007 0 00-2.088-2.088c-1.87-.501-9.396-.501-9.396-.501s-7.507-.01-9.396.501A3.007 3.007 0 00.527 6.205a31.247 31.247 0 00-.522 5.805 31.247 31.247 0 00.522 5.783 3.007 3.007 0 002.088 2.088c1.868.502 9.396.502 9.396.502s7.506 0 9.396-.502a3.007 3.007 0 002.088-2.088 31.247 31.247 0 00.5-5.783 31.247 31.247 0 00-.5-5.805zM9.609 15.601V8.408l6.264 3.602z" />
) : (
icon === 'vimeo' && (
<path d="M23.977 6.416c-.105 2.338-1.739 5.543-4.894 9.609-3.268 4.247-6.026 6.37-8.29 6.37-1.409 0-2.578-1.294-3.553-3.881L5.322 11.4C4.603 8.816 3.834 7.522 3.01 7.522c-.179 0-.806.378-1.881 1.132L0 7.197a315.065 315.065 0 003.501-3.128C5.08 2.701 6.266 1.984 7.055 1.91c1.867-.18 3.016 1.1 3.447 3.838.465 2.953.789 4.789.971 5.507.539 2.45 1.131 3.674 1.776 3.674.502 0 1.256-.796 2.265-2.385 1.004-1.589 1.54-2.797 1.612-3.628.144-1.371-.395-2.061-1.614-2.061-.574 0-1.167.121-1.777.391 1.186-3.868 3.434-5.757 6.762-5.637 2.473.06 3.628 1.664 3.493 4.797l-.013.01z" />
)
)}
</svg>
);
}
}
title: 10 Essential React Interview Questions template: post subtitle: For Aspiring Frontend Developers excerpt: Comprehensive React Cheatsheet included at the bottom of this article! date: 2022-05-08T18:44:35.533Z image: https://deploy-preview-2286--bgoonz-blog.netlify.app/images/react.gif thumb_image: https://deploy-preview-2286--bgoonz-blog.netlify.app/images/react.gif image_position: right author: src/data/authors/bgoonz.yaml categories:
- src/data/categories/react.yaml
- src/data/categories/js.yaml
tags:
- src/data/tags/react.yaml
- src/data/tags/javascript.yaml
show_author_bio: true related_posts:
- src/pages/blog/react-semantics.md
- src/pages/blog/react-state.md
cmseditable: true
10 Essential React Interview Questions For Aspiring Frontend Developers
Comprehensive React Cheatsheet included at the bottom of this article!
10 Essential React Interview Questions For Aspiring Frontend Developers
Comprehensive React Cheatsheet included at the bottom of this article!
Resources:
Introduction to React for Complete Beginners
All of the code examples below will be included a second time at the bottom of this article as an embedded gist.javascript.plainenglish.io
Beginner's Guide To React Part 2
As I learn to build web applications in React I will blog about it in this series in an attempt to capture theâŠ
A JavaScript library for building user interfaces Declarative React makes it painless to create interactive UIs. DesignâŠgithub.com
A JavaScript library for building user interfacesreactjs.org
Also ⊠here is my brand new blog site⊠built with react and a static site generator called GatsbyJS!
It's a work in progress
https://bgoonz-blog.netlify.app/
Pros
- Easy to learn
- HTML-like syntax allows templating and highly detailed documentation
- Supports server-side rendering
- Easy migrating between different versions of React
- Uses JavaScript rather than framework-specific code
Cons
- Poor documentation
- Limited to only view part of MVC
- New developers might see JSC as a barrier
Where to Use React
- For apps that have multiple events
- When your app development team excels in CSS, JavaScript and HTML
- You want to create sharable components on your app
- When you need a personalized app solution
Misconceptions about React
React is a framework:
Many developers and aspiring students misinterpret React to be a fully functional framework. It is because we often compare React with major frameworks such as Angular and Ember. This comparison is not to compare the best frameworks but to focus on the differences and similarities of React and Angular's approach that makes their offerings worth studying. Angular works on the MVC model to support the Model, View, and Controller layers of an app. React focuses only on the 'V,' which is the view layer of an application and how to make handling it easier to integrate smoothly into a project.
React's Virtual DOM is faster than DOM.
React uses a Virtual DOM, which is essentially a tree of JavaScript objects representing the actual browser DOM. The advantage of using this for the developers is that they don't manipulate the DOM directly as developers do with jQuery when they write React apps. Instead, they would tell React how they want the DOM to make changes to the state object and allow React to make the necessary updates to the browser DOM. This helps create a comprehensive development model for developers as they don't need to track all DOM changes. They can modify the state object, and React would use its algorithms to understand what part of UI changed compared to the previous DOM. Using this information updates the actual browser DOM. Virtual DOM provides an excellent API for creating UI and minimizes the update count to be made on the browser DOM.
However, it is not faster than the actual DOM. You just read that it needs to pull extra strings to figure out what part of UI needs to be updated before actually performing those updates. Hence, Virtual DOM is beneficial for many things, but it isn't faster than DOM.
1. Explain how React uses a tree data structure called the virtual DOM to model the DOM
The virtual DOM is a copy of the actual DOM tree. Updates in React are made to the virtual DOM. React uses a diffing algorithm to reconcile the changes and send the to the DOM to commit and paint.
2. Create virtual DOM nodes using JSX To create a React virtual DOM node using JSX, define HTML syntax in a JavaScript file.
Here, the JavaScript hello variable is set to a React virtual DOM h1 element with the text "Hello World!".
You can also nest virtual DOM nodes in each other just like how you do it in HTML with the real DOM.
3. Use debugging tools to determine when a component is rendering
4. Describe how JSX transforms into actual DOM nodes
- To transfer JSX into DOM nodes, we use the ReactDOM.render method. It takes a React virtual DOM node's changes allows Babel to transpile it and sends the JS changes to commit to the DOM.
5. Use the ReactDOM.render method to have React render your virtual DOM nodes under an actual DOM node
6. Attach an event listener to an actual DOM node using a virtual node
The virtual DOM (VDOM) is a programming concept where an ideal, or "virtual", representation of a UI is kept in memory and synced with the "real" DOM by a library such as ReactDOM. This process is called reconciliation.
This approach enables the declarative API of React: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app.
Since "virtual DOM" is more of a pattern than a specific technology, people sometimes say it to mean different things. In React world, the term "virtual DOM" is usually associated with React elements since they are the objects representing the user interface. React, however, also uses internal objects called "fibers" to hold additional information about the component tree. They may also be considered a part of "virtual DOM" implementation in React.
Is the Shadow DOM the same as the Virtual DOM?
No, they are different. The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
- To add an event listener to an element, define a method to handle the event and associate that method with the element event you want to listen for:
7. Use create-react-app to initialize a new React app and import required dependencies
- Create the default create-react-application by typing in our terminal
Explanation of npm vs npx from Free Code Camp:
npm (node package manager) is the dependency/package manager you get out of the box when you install Node.js. It provides a way for developers to install packages both globally and locally.
Sometimes you might want to take a look at a specific package and try out some commands. But you cannot do that without installing the dependencies in your local node_modules folder.
npm the package manager
npm is a couple of things. First and foremost, it is an online repository for the publishing of open-source Node.js projects.
Second, it is a CLI tool that aids you to install those packages and manage their versions and dependencies. There are hundreds of thousands of Node.js libraries and applications on npm and many more are added every day.
npm by itself doesn't run any packages. If you want to run a package using npm, you must specify that package in your package.json file.
When executables are installed via npm packages, npm creates links to them:
- local installs have links created at the
./node_modules/.bin/directory - global installs have links created from the global
bin/directory (for example:/usr/local/binon Linux or at%AppData%/npmon Windows)
To execute a package with npm you either have to type the local path, like this:
$ ./node_modules/.bin/your-package
or you can run a locally installed package by adding it into your package.json file in the scripts section, like this:
{
"name": "your-application",
"version": "1.0.0",
"scripts": {
"your-package": "your-package"
}
}
Then you can run the script using npm run:
npm run your-package
You can see that running a package with plain npm requires quite a bit of ceremony.
Fortunately, this is where npx comes in handy.
npx the package runner
Since npm version 5.2.0 npx is pre-bundled with npm. So it's pretty much a standard nowadays.
npx is also a CLI tool whose purpose is to make it easy to install and manage dependencies hosted in the npm registry.
It's now very easy to run any sort of Node.js-based executable that you would normally install via npm.
You can run the following command to see if it is already installed for your current npm version:
$ which npx
If it's not, you can install it like this:
$ npm install -g npx
Once you make sure you have it installed, let's see a few of the use cases that make npx extremely helpful.
Run a locally installed package easily
If you wish to execute a locally installed package, all you need to do is type:
$ npx your-package
npx will check whether <command> or <package> exists in $PATH, or in the local project binaries, and if so it will execute it.
Execute packages that are not previously installed
Another major advantage is the ability to execute a package that wasn't previously installed.
Sometimes you just want to use some CLI tools but you don't want to install them globally just to test them out. This means you can save some disk space and simply run them only when you need them. This also means your global variables will be less polluted.
Now, where were we?
npx create-react-app <name of app> --use-npm
- npx gives us the latest version.
--use-npmjust means to use npm instead of yarn or some other package manager
8. Pass props into a React component
propsis an object that gets passed down from the parent component to the child component. The values can be of any data structure including a function (which is an object)
- You can also interpolate values into JSX.
- Set a variable to the string, "world", and replace the string of "world" in the NavLinks JSX element with the variable wrapped in curly braces:
Accessing props:
To access our props object in another component we pass it the props argument and React will invoke the functional component with the props object.
Reminder:
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
Function and Class Components
The simplest way to define a component is to write a JavaScript function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
This function is a valid React component because it accepts a single "props" (which stands for properties) object argument with data and returns a React element. We call such components "function components" because they are literally JavaScript functions.
You can also use an ES6 class to define a component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
The above two components are equivalent from React's point of view.
- You can pass down as many props keys as you want.
9. Destructure props
You can destructure the props object in the function component's parameter.
10. Create routes using components from the react-router-dom package
a. Import the react-router-dom package:
npm i react-router-dom
In your index.js:
- Above you import your BrowserRouter with which you can wrap your entire route hierarchy. This makes routing information from React Router available to all its descendent components.
- Then in the component of your choosing, usually top tier such as App.js, you can create your routes using the Route and Switch Components
Discover More:
Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method ofâŠbgoonz-blog.netlify.app
REACT CHEAT SHEET:
More content at plainenglish.io
By Bryan Guner on June 11, 2021.
August 31, 2021.
title: React Interview Questions & Answers subtitle: lorem-ipsum date: '2021-11-24' thumb_image_alt: image of excerpt: lorem-ipsum seo: title: 'React Interview Questions & Answers' description: '' robots: [] extra: [] template: post
thumb_image: images/es6.jpg
React Interview Questions & Answers
Questions Table
Table of Contents
| No. | Questions | Answer | |
|---|---|---|---|
| Core React | false | ||
| 1 | What is React? | false | |
| 2 | What are the major features of React? | false | |
| 3 | What is JSX? | false | |
| 4 | What is the difference between Element and Component? | false | |
| 5 | How to create components in React? | false | |
| 6 | When to use a Class Component over a Function Component? | false | |
| 7 | What are Pure Components? | false | |
| 8 | What is state in React? | false | |
| 9 | What are props in React? | false | |
| 10 | What is the difference between state and props? | false | |
| 11 | Why should we not update the state directly? | false | |
| 12 | What is the purpose of callback function as an argument of setState()? | false | |
| 13 | What is the difference between HTML and React event handling? | false | |
| 14 | How to bind methods or event handlers in JSX callbacks? | false | |
| 15 | How to pass a parameter to an event handler or callback? | false | |
| 16 | What are synthetic events in React? | false | |
| 17 | What are inline conditional expressions? | false | |
| 18 | What is "key" prop and what is the benefit of using it in arrays of elements? | false | |
| 19 | What is the use of refs? | false | |
| 20 | How to create refs? | false | |
| 21 | What are forward refs? | false | |
| 22 | Which is preferred option with in callback refs and findDOMNode()? | false | |
| 23 | Why are String Refs legacy? | false | |
| 24 | What is Virtual DOM? | false | |
| 25 | How Virtual DOM works? | false | |
| 26 | What is the difference between Shadow DOM and Virtual DOM? | false | |
| 27 | What is React Fiber? | false | |
| 28 | What is the main goal of React Fiber? | false | |
| 29 | What are controlled components? | false | |
| 30 | What are uncontrolled components? | false | |
| 31 | What is the difference between createElement and cloneElement? | false | |
| 32 | What is Lifting State Up in React? | false | |
| 33 | What are the different phases of component lifecycle? | false | |
| 34 | What are the lifecycle methods of React? | false | |
| 35 | What are Higher-Order components? | false | |
| 36 | How to create props proxy for HOC component? | false | |
| 37 | What is context? | false | |
| 38 | What is children prop? | false | |
| 39 | How to write comments in React? | false | |
| 40 | What is the purpose of using super constructor with props argument? | false | |
| 41 | What is reconciliation? | false | |
| 42 | How to set state with a dynamic key name? | false | |
| 43 | What would be the common mistake of function being called every time the component renders? | false | |
| 44 | Is lazy function supports named exports? | false | |
| 45 | Why React uses className over class attribute? | false | |
| 46 | What are fragments? | false | |
| 47 | Why fragments are better than container divs? | false | |
| 48 | What are portals in React? | false | |
| 49 | What are stateless components? | false | |
| 50 | What are stateful components? | false | |
| 51 | How to apply validation on props in React? | false | |
| 52 | What are the advantages of React? | false | |
| 53 | What are the limitations of React? | false | |
| 54 | What are error boundaries in React v16 | false | |
| 55 | How error boundaries handled in React v15? | false | |
| 56 | What are the recommended ways for static type checking? | false | |
| 57 | What is the use of react-dom package? | false | |
| 58 | What is the purpose of render method of react-dom? | false | |
| 59 | What is ReactDOMServer? | false | |
| 60 | How to use InnerHtml in React? | false | |
| 61 | How to use styles in React? | false | |
| 62 | How events are different in React? | false | |
| 63 | What will happen if you use setState in constructor? | false | |
| 64 | What is the impact of indexes as keys? | false | |
| 65 | Is it good to use setState() in componentWillMount() method? | false | |
| 66 | What will happen if you use props in initial state? | false | |
| 67 | How do you conditionally render components? | false | |
| 68 | Why we need to be careful when spreading props on DOM elements?? | false | |
| 69 | How you use decorators in React? | false | |
| 70 | How do you memoize a component? | false | |
| 71 | How you implement Server-Side Rendering or SSR? | false | |
| 72 | How to enable production mode in React? | false | |
| 73 | What is CRA and its benefits? | false | |
| 74 | What is the lifecycle methods order in mounting? | false | |
| 75 | What are the lifecycle methods going to be deprecated in React v16? | false | |
| 76 | What is the purpose of getDerivedStateFromProps() lifecycle method? | false | |
| 77 | What is the purpose of getSnapshotBeforeUpdate() lifecycle method? | false | |
| 78 | Do Hooks replace render props and higher order components? | false | |
| 79 | What is the recommended way for naming components? | false | |
| 80 | What is the recommended ordering of methods in component class? | false | |
| 81 | What is a switching component? | false | |
| 82 | Why we need to pass a function to setState()? | false | |
| 83 | What is strict mode in React? | false | |
| 84 | What are React Mixins? | false | |
| 85 | Why is isMounted() an anti-pattern and what is the proper solution? | false | |
| 86 | What are the Pointer Events supported in React? | false | |
| 87 | Why should component names start with capital letter? | false | |
| 88 | Are custom DOM attributes supported in React v16? | false | |
| 89 | What is the difference between constructor and getInitialState? | false | |
| 90 | Can you force a component to re-render without calling setState? | false | |
| 91 | What is the difference between super() and super(props) in React using ES6 classes? | false | |
| 92 | How to loop inside JSX? | false | |
| 93 | How do you access props in attribute quotes? | false | |
| 94 | What is React PropType array with shape? | false | |
| 95 | How to conditionally apply class attributes? | false | |
| 96 | What is the difference between React and ReactDOM? | false | |
| 97 | Why ReactDOM is separated from React? | false | |
| 98 | How to use React label element? | false | |
| 99 | How to combine multiple inline style objects? | false | |
| 100 | How to re-render the view when the browser is resized? | false | |
| 101 | What is the difference between setState and replaceState methods? | false | |
| 102 | How to listen to state changes? | false | |
| 103 | What is the recommended approach of removing an array element in react state? | false | |
| 104 | Is it possible to use React without rendering HTML? | false | |
| 105 | How to pretty print JSON with React? | false | |
| 106 | Why you can't update props in React? | false | |
| 107 | How to focus an input element on page load? | false | |
| 108 | What are the possible ways of updating objects in state? | false | |
| 110 | How can we find the version of React at runtime in the browser? | false | |
| 111 | What are the approaches to include polyfills in your create-react-app? | false | |
| 112 | How to use https instead of http in create-react-app? | false | |
| 113 | How to avoid using relative path imports in create-react-app? | false | |
| 114 | How to add Google Analytics for react-router? | false | |
| 115 | How to update a component every second? | false | |
| 116 | How do you apply vendor prefixes to inline styles in React? | false | |
| 117 | How to import and export components using react and ES6? | false | |
| 118 | What are the exceptions on React component naming? | false | |
| 119 | Why is a component constructor called only once? | false | |
| 120 | How to define constants in React? | false | |
| 121 | How to programmatically trigger click event in React? | false | |
| 122 | Is it possible to use async/await in plain React? | false | |
| 123 | What are the common folder structures for React? | false | |
| 124 | What are the popular packages for animation? | false | |
| 125 | What is the benefit of styles modules? | false | |
| 126 | What are the popular React-specific linters? | false | |
| 127 | How to make AJAX call and In which component lifecycle methods should I make an AJAX call? | false | |
| 128 | What are render props? | false | |
| React Router | false | ||
| 129 | What is React Router? | false | |
| 130 | How React Router is different from history library? | false | |
| 131 | What are the <Router> components of React Router v4? | false | |
| 132 | What is the purpose of push and replace methods of history? | false | |
| 133 | How do you programmatically navigate using React router v4? | false | |
| 134 | How to get query parameters in React Router v4 | false | |
| 135 | Why you get "Router may have only one child element" warning? | false | |
| 136 | How to pass params to history.push method in React Router v4? | false | |
| 137 | How to implement default or NotFound page? | false | |
| 138 | How to get history on React Router v4? | false | |
| 139 | How to perform automatic redirect after login? | false | |
| React Internationalization | false | ||
| 140 | What is React-Intl? | false | |
| 141 | What are the main features of React Intl? | false | |
| 142 | What are the two ways of formatting in React Intl? | false | |
| 143 | How to use FormattedMessage as placeholder using React Intl? | false | |
| 144 | How to access current locale with React Intl | false | |
| 145 | How to format date using React Intl? | false | |
| React Testing | false | ||
| 146 | What is Shallow Renderer in React testing? | false | |
| 147 | What is TestRenderer package in React? | false | |
| 148 | What is the purpose of ReactTestUtils package? | false | |
| 149 | What is Jest? | false | |
| 150 | What are the advantages of Jest over Jasmine? | false | |
| 151 | Give a simple example of Jest test case | false | |
| React Redux | false | ||
| 152 | What is Flux? | false | |
| 153 | What is Redux? | false | |
| 154 | What are the core principles of Redux? | false | |
| 155 | What are the downsides of Redux compared to Flux? | false | |
| 156 | What is the difference between mapStateToProps() and mapDispatchToProps()? | false | |
| 157 | Can I dispatch an action in reducer? | false | |
| 158 | How to access Redux store outside a component? | false | |
| 159 | What are the drawbacks of MVW pattern | false | |
| 160 | Are there any similarities between Redux and RxJS? | false | |
| 161 | How to dispatch an action on load? | false | |
| 162 | How to use connect from React Redux? | false | |
| 163 | How to reset state in Redux? | false | |
| 164 | Whats the purpose of at symbol in the redux connect decorator? | false | |
| 165 | What is the difference between React context and React Redux? | false | |
| 166 | Why are Redux state functions called reducers? | false | |
| 167 | How to make AJAX request in Redux? | false | |
| 168 | Should I keep all component's state in Redux store? | false | |
| 169 | What is the proper way to access Redux store? | false | |
| 170 | What is the difference between component and container in React Redux? | false | |
| 171 | What is the purpose of the constants in Redux? | false | |
| 172 | What are the different ways to write mapDispatchToProps()? | false | |
| 173 | What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? | false | |
| 174 | How to structure Redux top level directories? | false | |
| 175 | What is redux-saga? | false | |
| 176 | What is the mental model of redux-saga? | false | |
| 177 | What are the differences between call and put in redux-saga | false | |
| 178 | What is Redux Thunk? | false | |
| 179 | What are the differences between redux-saga and redux-thunk | false | |
| 180 | What is Redux DevTools? | false | |
| 181 | What are the features of Redux DevTools? | false | |
| 182 | What are Redux selectors and Why to use them? | false | |
| 183 | What is Redux Form? | false | |
| 184 | What are the main features of Redux Form? | false | |
| 185 | How to add multiple middlewares to Redux? | false | |
| 186 | How to set initial state in Redux? | false | |
| 187 | How Relay is different from Redux? | false | |
| 188 | What is an action in Redux? | false | |
| React Native | false | ||
| 188 | What is the difference between React Native and React? | false | |
| 189 | How to test React Native apps? | false | |
| 190 | How to do logging in React Native? | false | |
| 191 | How to debug your React Native? | false | |
| React supported libraries and Integration | false | ||
| 192 | What is reselect and how it works? | false | |
| 193 | What is Flow? | false | |
| 194 | What is the difference between Flow and PropTypes? | false | |
| 195 | How to use font-awesome icons in React? | false | |
| 196 | What is React Dev Tools? | false | |
| 197 | Why is DevTools not loading in Chrome for local files? | false | |
| 198 | How to use Polymer in React? | false | |
| 199 | What are the advantages of React over Vue.js? | false | |
| 200 | What is the difference between React and Angular? | false | |
| 201 | Why React tab is not showing up in DevTools? | false | |
| 202 | What are styled components? | false | |
| 203 | Give an example of Styled Components? | false | |
| 204 | What is Relay? | false | |
| 205 | How to use TypeScript in create-react-app application? | false | |
| Miscellaneous | false | ||
| 206 | What are the main features of reselect library? | false | |
| 207 | Give an example of reselect usage? | false | |
| 209 | Does the statics object work with ES6 classes in React? | false | |
| 210 | Can Redux only be used with React? | false | |
| 211 | Do you need to have a particular build tool to use Redux? | false | |
| 212 | How Redux Form initialValues get updated from state? | false | |
| 213 | How React PropTypes allow different type for one prop? | false | |
| 214 | Can I import an SVG file as react component? | false | |
| 215 | Why are inline ref callbacks or functions not recommended? | false | |
| 216 | What is render hijacking in React? | false | |
| 217 | What are HOC factory implementations? | false | |
| 218 | How to pass numbers to React component? | false | |
| 219 | Do I need to keep all my state into Redux? Should I ever use react internal state? | false | |
| 220 | What is the purpose of registerServiceWorker in React? | false | |
| 221 | What is React memo function? | false | |
| 222 | What is React lazy function? | false | |
| 223 | How to prevent unnecessary updates using setState? | false | |
| 224 | How do you render Array, Strings and Numbers in React 16 Version? | false | |
| 225 | How to use class field declarations syntax in React classes? | false | |
| 226 | What are hooks? | false | |
| 227 | What are the rules needs to follow for hooks? | false | |
| 228 | How to ensure hooks followed the rules in your project? | false | |
| 229 | What are the differences between Flux and Redux? | false | |
| 230 | What are the benefits of React Router V4? | false | |
| 231 | Can you describe about componentDidCatch lifecycle method signature? | false | |
| 232 | In which scenarios error boundaries do not catch errors? | false | |
| 233 | Why do you not need error boundaries for event handlers? | false | |
| 234 | What is the difference between try catch block and error boundaries? | false | |
| 235 | What is the behavior of uncaught errors in react 16? | false | |
| 236 | What is the proper placement for error boundaries? | false | |
| 237 | What is the benefit of component stack trace from error boundary? | false | |
| 238 | What is the required method to be defined for a class component? | false | |
| 239 | What are the possible return types of render method? | false | |
| 240 | What is the main purpose of constructor? | false | |
| 241 | Is it mandatory to define constructor for React component? | false | |
| 242 | What are default props? | false | |
| 243 | Why should not call setState in componentWillUnmount? | false | |
| 244 | What is the purpose of getDerivedStateFromError? | false | |
| 245 | What is the methods order when component re-rendered? | false | |
| 246 | What are the methods invoked during error handling? | false | |
| 247 | What is the purpose of displayName class property? | false | |
| 248 | What is the browser support for react applications? | false | |
| 249 | What is the purpose of unmountComponentAtNode method? | false | |
| 250 | What is code-splitting? | false | |
| 251 | What is the benefit of strict mode? | false | |
| 252 | What are Keyed Fragments? | false | |
| 253 | Does React support all HTML attributes? | false | |
| 254 | What are the limitations with HOCs? | false | |
| 255 | How to debug forwardRefs in DevTools? | false | |
| 256 | When component props defaults to true? | false | |
| 257 | What is NextJS and major features of it? | false | |
| 258 | How do you pass an event handler to a component? | false | |
| 259 | Is it good to use arrow functions in render methods? | false | |
| 260 | How to prevent a function from being called multiple times? | false | |
| 261 | How JSX prevents Injection Attacks? | false | |
| 262 | How do you update rendered elements? | false | |
| 263 | How do you say that props are read only? | false | |
| 264 | How do you say that state updates are merged? | false | |
| 265 | How do you pass arguments to an event handler? | false | |
| 266 | How to prevent component from rendering? | false | |
| 267 | What are the conditions to safely use the index as a key? | false | |
| 268 | Is it keys should be globally unique? | false | |
| 269 | What is the popular choice for form handling? | false | |
| 270 | What are the advantages of formik over redux form library? | false | |
| 271 | Why do you not required to use inheritance? | false | |
| 272 | Can I use web components in react application? | false | |
| 273 | What is dynamic import? | false | |
| 274 | What are loadable components? | false | |
| 275 | What is suspense component? | false | |
| 276 | What is route based code splitting? | false | |
| 277 | Give an example on How to use context? | false | |
| 278 | What is the purpose of default value in context? | false | |
| 279 | How do you use contextType? | false | |
| 280 | What is a consumer? | false | |
| 281 | How do you solve performance corner cases while using context? | false | |
| 282 | What is the purpose of forward ref in HOCs? | false | |
| 283 | Is it ref argument available for all functions or class components? | false | |
| 284 | Why do you need additional care for component libraries while using forward refs? | false | |
| 285 | How to create react class components without ES6? | false | |
| 286 | Is it possible to use react without JSX? | false | |
| 287 | What is diffing algorithm? | false | |
| 288 | What are the rules covered by diffing algorithm? | false | |
| 289 | When do you need to use refs? | false | |
| 290 | Is it prop must be named as render for render props? | false | |
| 291 | What are the problems of using render props with pure components? | false | |
| 292 | How do you create HOC using render props? | false | |
| 293 | What is windowing technique? | false | |
| 294 | How do you print falsy values in JSX? | false | |
| 295 | What is the typical use case of portals? | false | |
| 296 | How do you set default value for uncontrolled component? | false | |
| 297 | What is your favorite React stack? | false | |
| 298 | What is the difference between Real DOM and Virtual DOM? | false | |
| 299 | How to add Bootstrap to a react application? | false | |
| 300 | Can you list down top websites or applications using react as front end framework? | false | |
| 301 | Is it recommended to use CSS In JS technique in React? | false | |
| 302 | Do I need to rewrite all my class components with hooks? | false | |
| 303 | How to fetch data with React Hooks? | false | |
| 304 | Is Hooks cover all use cases for classes? | false | |
| 305 | What is the stable release for hooks support? | false | |
| 306 | Why do we use array destructuring (square brackets notation) in useState? | false | |
| 307 | What are the sources used for introducing hooks? | false | |
| 308 | How do you access imperative API of web components? | false | |
| 309 | What is formik? | false | |
| 310 | What are typical middleware choices for handling asynchronous calls in Redux? | false | |
| 311 | Do browsers understand JSX code? | false | |
| 312 | Describe about data flow in react? | false | |
| 313 | What is react scripts? | false | |
| 314 | What are the features of create react app? | false | |
| 315 | What is the purpose of renderToNodeStream method? | false | |
| 316 | What is MobX? | false | |
| 317 | What are the differences between Redux and MobX? | false | |
| 318 | Should I learn ES6 before learning ReactJS? | false | |
| 319 | What is Concurrent Rendering? | false | |
| 320 | What is the difference between async mode and concurrent mode? | false | |
| 321 | Can I use javascript urls in react16.9? | false | |
| 322 | What is the purpose of eslint plugin for hooks? | false | |
| 323 | What is the difference between Imperative and Declarative in React? | false | |
| 324 | What are the benefits of using typescript with reactjs? | false | |
| 325 | How do you make sure that user remains authenticated on page refresh while using Context API State Management? | false | |
| 326 | What are the benefits of new JSX transform? | false | |
| 327 | How does new JSX transform different from old transform? | false | |
| 328 | How do you get redux scaffolding using create-react-app? | false | |
| 329 | What are React Server components? | false |
title: Container With Most Water weight: 0 excerpt: feel free to try the examples seo: title: ' Container With Most Water ' description: Leetcode practice robots: [] extra: [] type: stackbit_page_meta
template: docs
[11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/description
/)
Problem:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Solution:
Greedy Algorithm.
If we look at the simple brute force approach, where we choose one point at a time and calculate all the possible areas with other points on the right, it is easy to make a observation that we are narrowing down the horizontal distance.
Greedy Algorithm can help us skip some of the conditions. It is base on a fact that the area between two columns are determined by the shorter one.
Let's say we have pointer l and r at the begin and end of a distance, and the area is area(l, r), how should we narrow down the distance?
If height[l] < height[r], we know that the height of the area will never be greater than height[l] if we keep l. Now if we get rid of r, the area can only get smaller since the distance is shorter, and the height is at most height[l].
Here we conclude rule NO.1: Get rid of the smaller one.
What if height[l] == height[r]? It is safe to get rid of both. We do not need any of them to constrain the max height of the rest points.
//
/**
* @param {number[]} height
* @return {number}
*/
let maxArea = function (height) {
let max = 0;
for (let l = 0, r = height.length - 1; l < r; l++, r--) {
max = Math.max(max, (r - l) * Math.min(height[l], height[r]));
if (height[l] < height[r]) {
r++;
} else {
l--;
}
}
return max;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Divide Two Integers weight: 0 excerpt: feel free to try the examples seo: title: 'Divide Two Integers' description: 'Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[29. Divide Two Integers](https://leetcode.com/problems/divide-two-integers/description
/)
Problem:
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [â231, 231 â 1]. For the purpose of this problem, assume that your function returns 231 â 1 when the division result overflows.
Solution:
Every decimal number can be represented as a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n.
Replace multiplication and division with binary shifting.
//
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
let divide = function (dividend, divisor) {
if (divisor === 0 || (divisor === -1 && dividend < -2147483647) || dividend > 2147483647 || dividend < -2147483648) {
return 2147483647;
}
const isNegative = (dividend < 0 && divisor >= 0) || (dividend >= 0 && divisor < 0);
const pDividend = Math.abs(dividend);
const pDivisor = Math.abs(divisor);
if (dividend === 0 || pDividend < pDivisor) {
return 0;
}
let doubling = pDivisor;
let count = 1;
while (doubling < pDividend && !(doubling & (1 << 30))) {
doubling <<= 1;
count <<= 1;
}
if (doubling > pDividend) {
doubling >>>= 1;
count >>>= 1;
}
const result = count + divide(pDividend - doubling, pDivisor);
return isNegative ? -result : result;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Emmet Cheat Sheet excerpt: In this section you'll find basic information about Web-Dev-Huband how to use it. seo: title: Emmet Cheat Sheet description: This is the Emmet Cheat Sheet page extra:
- name: 'og:type'
value: website
keyName: property
- name: 'og:title'
value: Emmet Cheat Sheet
keyName: property
- name: 'og:description'
value: This is the Emmet Cheat Sheet page
keyName: property
- name: 'twitter:card'
value: summary
- name: 'twitter:title'
value: Emmet Cheat Sheet
- name: 'twitter:description'
value: This is the Emmet Cheat Sheet page
template: docs
Emmet Cheat Sheet
EMMET
Emmet Cheat Sheet
EMMET
The a toolkit for web-developers
Introduction
Emmet is a productivity toolkit for web developers that uses expressions to generate HTML snippets.
Installation
Normally, installation for Emmet should be a straight-forward process from the package-manager, as most of the modern text editors support Emmet.
Usage
You can use Emmet in two ways:
- Tab Expand Way: Type your emmet code and press
Tabkey - Interactive Method: Press
alt + ctrl + Enterand start typing your expressions. This should automatically generate HTML snippets on the fly.
This cheatsheet will assume that you pressTabafter each expressions.
HTML
Generating HTML 5 DOCTYPE
html:5
Will generate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
Child items
Child items are created using >
ul>li>p
<ul>
<li>
<p>
Sibling Items
Sibling items are created using +
html>head+body
<html>
<head>
</body>
</html>
Multiplication
Items can be multiplied by *
ul>li*5
<ul>
<li>
Grouping
Items can be grouped together using ()
table>(tr>th*5)+tr>t*5
<table>
<tr>
<th>
Class and ID
Class and Id in Emmet can be done using . and #
div.heading
<div class="heading">
div#heading
<div id="heading">
ID and Class can also be combined together
div#heading.center
<div id="heading" class="center">
Adding Content inside tags
Contents inside tags can be added using {}
h1{Emmet is awesome}+h2{Every front end developers should use this}+p{This is paragraph}*2
<h1>Emmet is awesome</h1>
<h2>Every front end developers should use this</h2>
<p>This is paragraph</p>
<p>This is paragraph</p>
Attributes inside HTML tags
Attributes can be added using []
a[href=https://?google.com data-toggle=something target=_blank]
<a href="https://?google.com" data-toggle="something" target="_blank">
Numbering
Numbering can be done using $
You can use this inside tag or contents.
h${This is so awesome $}*6
<h1>This is so awesome 1</h1>
<h2>This is so awesome 2</h2>
<h3>This is so awesome 3</h3>
<h4>This is so awesome 4</h4>
<h5>This is so awesome 5</h5>
<h6>This is so awesome 6</h6>
Use @- to reverse the Numbering
img[src=image$$@-.jpg]*5
<img src="image05.jpg" alt="">
<img src="image04.jpg" alt="">
<img src="image03.jpg" alt="">
<img src="image02.jpg" alt="">
<img src="image01.jpg" alt="">
To start the numbering from specific number, use this way
img[src=emmet$@100.jpg]*5
<img src="emmet100.jpg" alt="">
<img src="emmet101.jpg" alt="">
<img src="emmet102.jpg" alt="">
<img src="emmet103.jpg" alt="">
<img src="emmet104.jpg" alt="">
Tips
- Use
:to expand known abbreviations
input:date
<input type="date" name="" id="">
form:post
<form action="" method="post">
link:css
<link rel="stylesheet" href="style.css">
- Building Navbar
.navbar>ul>li*3>a[href=#]{Item $@-}
<div class="navbar">
<ul>
<li>
CSS
Emmet works surprisingly well with css as well.
f:l
float: left;
You can also use any options n/r/l
pos:aÂ
position: absolute;
Also use any options, pos:a/r/f
d:n/bÂ/f/Âi/ib
d:ib
display: inline-block;
- You can use
mfor margin andpfor padding followed by direction
mr -> margin-right
pr -> padding-right
@fwill result in
@font-face {
font-family:;
src:url();
}
You can also use these shorthands
bgoonzâââOverview
Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | SequelizeâŠgithub.com
Or Checkout my personal Resource Site:
a/A-Student-Resources
Edit descriptiongoofy-euclid-1cd736.netlify.app
By Bryan Guner on March 6, 2021.
May 23, 2021.
title: Emmet Cheat Sheet excerpt: In this section you'll find basic information about Web-Dev-Huband how to use it. seo: title: Emmet Cheat Sheet description: This is the Emmet Cheat Sheet page extra:
- name: 'og:type'
value: website
keyName: property
- name: 'og:title'
value: Emmet Cheat Sheet
keyName: property
- name: 'og:description'
value: This is the Emmet Cheat Sheet page
keyName: property
- name: 'twitter:card'
value: summary
- name: 'twitter:title'
value: Emmet Cheat Sheet
- name: 'twitter:description'
value: This is the Emmet Cheat Sheet page
template: docs
Emmet Cheat Sheet
EMMET
Emmet Cheat Sheet
EMMET
The a toolkit for web-developers
Introduction
Emmet is a productivity toolkit for web developers that uses expressions to generate HTML snippets.
Installation
Normally, installation for Emmet should be a straight-forward process from the package-manager, as most of the modern text editors support Emmet.
Usage
You can use Emmet in two ways:
- Tab Expand Way: Type your emmet code and press
Tabkey - Interactive Method: Press
alt + ctrl + Enterand start typing your expressions. This should automatically generate HTML snippets on the fly.
This cheatsheet will assume that you pressTabafter each expressions.
HTML
Generating HTML 5 DOCTYPE
html:5
Will generate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
Child items
Child items are created using >
ul>li>p
<ul>
<li>
<p>
Sibling Items
Sibling items are created using +
html>head+body
<html>
<head>
</body>
</html>
Multiplication
Items can be multiplied by *
ul>li*5
<ul>
<li>
Grouping
Items can be grouped together using ()
table>(tr>th*5)+tr>t*5
<table>
<tr>
<th>
Class and ID
Class and Id in Emmet can be done using . and #
div.heading
<div class="heading">
div#heading
<div id="heading">
ID and Class can also be combined together
div#heading.center
<div id="heading" class="center">
Adding Content inside tags
Contents inside tags can be added using {}
h1{Emmet is awesome}+h2{Every front end developers should use this}+p{This is paragraph}*2
<h1>Emmet is awesome</h1>
<h2>Every front end developers should use this</h2>
<p>This is paragraph</p>
<p>This is paragraph</p>
Attributes inside HTML tags
Attributes can be added using []
a[href=https://?google.com data-toggle=something target=_blank]
<a href="https://?google.com" data-toggle="something" target="_blank">
Numbering
Numbering can be done using $
You can use this inside tag or contents.
h${This is so awesome $}*6
<h1>This is so awesome 1</h1>
<h2>This is so awesome 2</h2>
<h3>This is so awesome 3</h3>
<h4>This is so awesome 4</h4>
<h5>This is so awesome 5</h5>
<h6>This is so awesome 6</h6>
Use @- to reverse the Numbering
img[src=image$$@-.jpg]*5
<img src="image05.jpg" alt="">
<img src="image04.jpg" alt="">
<img src="image03.jpg" alt="">
<img src="image02.jpg" alt="">
<img src="image01.jpg" alt="">
To start the numbering from specific number, use this way
img[src=emmet$@100.jpg]*5
<img src="emmet100.jpg" alt="">
<img src="emmet101.jpg" alt="">
<img src="emmet102.jpg" alt="">
<img src="emmet103.jpg" alt="">
<img src="emmet104.jpg" alt="">
Tips
- Use
:to expand known abbreviations
input:date
<input type="date" name="" id="">
form:post
<form action="" method="post">
link:css
<link rel="stylesheet" href="style.css">
- Building Navbar
.navbar>ul>li*3>a[href=#]{Item $@-}
<div class="navbar">
<ul>
<li>
CSS
Emmet works surprisingly well with css as well.
f:l
float: left;
You can also use any options n/r/l
pos:aÂ
position: absolute;
Also use any options, pos:a/r/f
d:n/bÂ/f/Âi/ib
d:ib
display: inline-block;
- You can use
mfor margin andpfor padding followed by direction
mr -> margin-right
pr -> padding-right
@fwill result in
@font-face {
font-family:;
src:url();
}
You can also use these shorthands
bgoonzâââOverview
Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | SequelizeâŠgithub.com
Or Checkout my personal Resource Site:
a/A-Student-Resources
Edit descriptiongoofy-euclid-1cd736.netlify.app
By Bryan Guner on March 6, 2021.
May 23, 2021.
title: Generate Parentheses weight: 0 excerpt: feel free to try the examples seo: title: ' Generate Parentheses ' description: ' Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. ' robots: [] extra: [] type: stackbit_page_meta
template: docs
[22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/description
/)
Problem:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution:
ONE
Recursive DFS backtracking.
//
/**
* @param {number} n
* @return {string[]}
*/
let generateParenthesis = function (n) {
const result = [];
if (n > 0) {
dfs(n, 0, 0, '', result);
}
return result;
};
function dfs(n, nopen, nclose, path, result) {
if (path.length === n * 2) {
result.push(path);
return;
}
if (nopen < n) {
dfs(n, nopen + 1, nclose, path + '(', result);
}
if (nclose < nopen) {
dfs(n, nopen, nclose + 1, path + ')', result);
}
}
TWO
BFS.
//
/**
* @param {number} n
* @return {string[]}
*/
let generateParenthesis = function (n) {
if (n <= 0) {
return [];
}
const queue = [
{
path: '(',
open: 1,
close: 0
}
];
while (true) {
const { path, open, close } = queue.shift();
if (open + close === n * 2) {
queue.unshift({ path, open, close });
break;
}
if (open < n) {
queue.push({
path: path + '(',
open: open + 1,
close
});
}
if (close < open) {
queue.push({
path: path + ')',
open,
close: close + 1
});
}
}
return queue.map((x) => x.path);
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Letter Combinations of a Phone Number weight: 0 excerpt: feel free to try the examples seo: title: 'Letter Combinations of a Phone Number' description: 'Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description
/)
Problem:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
![]()
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Solution:
ONE
JavaScript specific optimization.
Array.prototype.push accepts arbitrary arguments which enables tighter loops.
Also, appending string is faster than prepending.
//
/**
* @param {string} digits
* @return {string[]}
*/
let letterCombinations = function (digits) {
if (digits.length <= 0) {
return [];
}
const letters = [
,
,
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']
];
let result = [''];
for (let i = 0; i < digits.length; i++) {
const arr = letters[digits[i]];
let newResult = [];
arr.forEach((c) => newResult.push(...result.map((r) => r + c)));
result = newResult;
}
return result;
};
TWO
General recursive DFS solution.
//
/**
* @param {string} digits
* @return {string[]}
*/
let letterCombinations = function (digits) {
const letters = [, , 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
const result = [];
if (digits.length > 0) {
dfs(digits, 0, '', letters, result);
}
return result;
};
function dfs(digits, idigit, path, letters, result) {
if (idigit >= digits.length) {
result.push(path);
return;
}
const str = letters[digits[idigit]];
for (let i = 0; i < str.length; i++) {
dfs(digits, idigit + 1, path + str[i], letters, result);
}
}
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Leetcode weight: 0 excerpt: feel free to try the examples seo: title: ' Longest Common Prefix' description: 'Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string ' robots: [] extra: [] type: stackbit_page_meta
template: docs
[14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description
/)
Problem:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Solution:
ONE
JavaScript specific solution. Get the min len then narrow down the prefix.
//
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function (strs) {
if (strs.length > 0) {
let minLen = Math.min(...strs.map((s) => s.length));
const anyStr = strs[0];
while (minLen) {
const prefix = anyStr.slice(0, minLen--);
if (strs.every((s) => s.startsWith(prefix))) {
return prefix;
}
}
}
return '';
};
TWO
//
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function (strs) {
if (strs.length <= 0) {
return '';
}
let i = 0;
while (strs.every((s) => s[i] && s[i] === strs[0][i])) {
i++;
}
return strs[0].slice(0, i);
};
THREE
General solution. Build up the prefix.
//
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function (strs) {
let prefix = '';
if (strs.length > 0) {
for (let i = 0; ; i++) {
const c = strs[0][i];
if (!c) {
return prefix;
}
for (let j = 0; j < strs.length; j++) {
if (strs[j][i] !== c) {
return prefix;
}
}
prefix += c;
}
}
return prefix;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Median of Two Sorted Arrays weight: 0 excerpt: feel free to try the examples seo: title: 'Median of Two Sorted Arrays' description: 'There are two sorted arrays nums1 and nums2 of size m and n respectively.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/description
/)
Problem:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Solution:
O(log (m+n)) means half of the sequence is ruled out on each loop. So obviously we need binary search.
To do it on two sorted arrays, we need a formula to guide division.
Let nums3 be the sorted array combining all the items in nums1 and nums2.
If nums2[j-1] <= nums1[i] <= nums2[j], then we know nums1[i] is at num3[i+j]. Same goes nums1[i-1] <= nums2[j] <= nums1[i].
Let k be â(m+n-1)/2â. We need to find nums3[k] (and also nums3[k+1] if m+n is even).
Let i + j = k, if we find nums2[j-1] <= nums1[i] <= nums2[j] or nums1[i-1] <= nums2[j] <= nums1[i], then we got k.
Otherwise, if nums1[i] <= nums2[j] then we know nums1[i] < nums2[j-1] (because we did not find k).
- There are
iitems beforenums1[i], andj-1items brefornums2[j-1], which meansnums1[0...i]are beforenums3[i+j-1]. So we now knownums1[0...i] < nums3[k]. They can be safely discarded. - We Also have
nums1[i] < nums2[j], which meansnums2[j...n)are afternums3[i+j]. Sonums2[j...n) > nums3[k].
Same goes nums1[i-1] <= nums2[j] <= nums1[i].
//
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
let findMedianSortedArrays = function (nums1, nums2) {
const mid = ((nums1.length + nums2.length - 1) / 2) | 0;
if ((nums1.length + nums2.length) % 2 === 0) {
return (_find(nums1, nums2, mid) + _find(nums1, nums2, mid + 1)) / 2;
}
return _find(nums1, nums2, mid);
};
function _find(nums1, nums2, k) {
if (nums1.length > nums2.length) {
// So that the `i` below is always smalller than k,
// which makes `j` always non-negative
[nums1, nums2] = [nums2, nums1];
}
let s1 = 0;
let s2 = 0;
let e1 = nums1.length;
let e2 = nums2.length;
while (s1 < e1 || s2 < e2) {
const i = s1 + (((e1 - s1) / 2) | 0);
const j = k - i;
const ni = i >= e1 ? Infinity : nums1[i];
const nj = j >= e2 ? Infinity : nums2[j];
const ni_1 = i <= 0 ? -Infinity : nums1[i - 1];
const nj_1 = j <= 0 ? -Infinity : nums2[j - 1];
if (nj_1 <= ni && ni <= nj) {
return ni;
}
if (ni_1 <= nj && nj <= ni) {
return nj;
}
if (ni <= nj) {
s1 = i + 1;
e2 = j;
} else {
s2 = j + 1;
e1 = i;
}
}
}
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Next Permutation weight: 0 excerpt: feel free to try the examples seo: title: 'Next Permutation' description: 'Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[31. Next Permutation](https://leetcode.com/problems/next-permutation/description
/)
Problem:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 â 1,3,23,2,1 â 1,2,31,1,5 â 1,5,1
Solution:
Observe a few longer examples and the pattern is self-evident.
Divide the list into two parts. The first half must be incremental and the second half must be decremental.
Reverse the second half and find the smallest number in it that is greater the last number of the first half.
Swap the two.
//
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
let nextPermutation = function (nums) {
const len = nums.length;
if (len <= 1) {
return;
}
for (let i = len - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
let t;
for (let s = i, e = len - 1; s < e; s++, e--) {
t = nums[s];
nums[s] = nums[e];
nums[e] = t;
}
let j = len - 1;
while (nums[j] <= nums[i - 1]) {
j--;
}
t = nums[j];
nums[j] = nums[i - 1];
nums[i - 1] = t;
break;
}
}
if (i === 0) {
nums.reverse();
}
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Palindrome Number weight: 0 excerpt: feel free to try the examples seo: title: 'Palindrome Number' description: 'Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[9. Palindrome Number](https://leetcode.com/problems/palindrome-number/description
/)
Problem:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
Solution:
ONE
Easy to write but slow since it generates an array.
//
/**
* @param {number} x
* @return {boolean}
*/
let isPalindrome = function (x) {
return x == String(x).split('').reverse().join('');
};
TWO
A bit faster.
//
/**
* @param {number} x
* @return {boolean}
*/
let isPalindrome = function (x) {
const s = String(x);
for (let i = 0, j = s.length - 1; i < j; i++, j--) {
if (s[i] !== s[j]) {
return false;
}
}
return true;
};
THREE
General solution. Combining 7. Reverse Integer.
//
/**
* @param {number} x
* @return {boolean}
*/
let isPalindrome = function (x) {
if (x < 0) {
return false;
}
return x === reverse(x);
};
/**
* @param {number} x
* @return {number}
*/
function reverse(x) {
let result = 0;
while (x) {
result = result * 10 + (x % 10);
x = (x / 10) | 0;
}
return result;
}
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Regular Expression Matching weight: 0 excerpt: feel free to try the examples seo: title: 'Regular Expression Matching' description: 'Given an input string (s) and a pattern (p), implement regular expression matching' robots: [] extra: [] type: stackbit_page_meta
template: docs
[10. Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/description
/)
Problem:
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
Solution:
ONE
Cheating with real RegExp matching.
//
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
let isMatch = function (s, p) {
if (p[0] === '*') {
return false;
}
return new RegExp(`^${p}$`).test(s);
};
TWO
Let f(i, j) be the matching result of s[0...i) and p[0...j).
//
f(0, j) =
j == 0 || // empty
p[j-1] == '*' && f(i, j-2) // matches 0 time, which matches empty string
f(i, 0) = false // pattern must cover the entire input string
f(i, j) =
if p[j-1] == '.'
f(i-1, j-1)
else if p[j-1] == '*'
f(i, j-2) || // matches 0 time
f(i-1, j) && (s[i-1] == p[j-2] || p[j-2] == '.') // matches 1 or multiple times
else
f(i-1, j-1) && s[i-1] == p[j-1]
//
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
let isMatch = function (s, p) {
if (p[0] === '*') {
return false;
}
const dp = [[true]];
for (let j = 2; j <= p.length; j++) {
dp[0][j] = p[j - 1] === '*' && dp[0][j - 2];
}
for (let i = 1; i <= s.length; i++) {
dp[i] = [];
for (let j = 1; j <= p.length; j++) {
switch (p[j - 1]) {
case '.':
dp[i][j] = dp[i - 1][j - 1];
break;
case '*':
dp[i][j] = dp[i][j - 2] || (dp[i - 1][j] && (p[j - 2] === '.' || s[i - 1] === p[j - 2]));
break;
default:
dp[i][j] = dp[i - 1][j - 1] && s[i - 1] === p[j - 1];
}
}
}
return !!dp[s.length][p.length];
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Remove Duplicates from Sorted Array weight: 0 excerpt: feel free to try the examples seo: title: 'Remove Duplicates from Sorted Array' description: 'Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description
/)
Problem:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Solution:
The result array can only be shorter. That is why we can build the array in-place with the new length.
//
/**
* @param {number[]} nums
* @return {number}
*/
let removeDuplicates = function (nums) {
let len = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== nums[i - 1]) {
nums[len++] = nums[i];
}
}
return len;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Remove Nth Node From End of List weight: 0 excerpt: feel free to try the examples seo: title: 'Remove Nth Node From End of List' description: 'Given a linked list, remove the n-th node from the end of list and return its head.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description
/)
Problem:
Given a linked list, remove the _n_-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given _n_ will always be valid.
Follow up:
Could you do this in one pass?
Solution:
Set a pointer p1 for iterating, and p2 which is n nodes behind, pointing at the (n+1)-th node from the end of list.
Boundaries that should be awared of:
p2could be one node beforehead, which means theheadshould be removed.p2could be larger than the length of the list (Though the description saysnwill always be valid, we take care of it anyway).- It should be
p1.nexttouches the end rather thanp1because we wantp1pointing at the last node.
//
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
let removeNthFromEnd = function (head, n) {
let p1 = head;
while (p1 && n--) {
p1 = p1.next;
}
if (!p1) {
return n ? head : head.next;
}
let p2 = head;
while (p1.next) {
p1 = p1.next;
p2 = p2.next;
}
p2.next = p2.next.next;
return head;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Roman to Integer weight: 0 excerpt: feel free to try the examples seo: title: 'Roman to Integer' description: 'Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/description
/)
Problem:
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Solution:
Normally we just add up the digits, except when the digit is greater than its left (e.g. IV). In that case we need to fallback and remove the last digit then combine the two as new digit. That is why we subtract the last digit twice.
//
/**
* @param {string} s
* @return {number}
*/
let romanToInt = function (s) {
const rdigit = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let result = 0;
for (let i = 0, lastDigit = Infinity; i < s.length; i++) {
let digit = rdigit[s[i]];
result += digit <= lastDigit ? digit : digit - lastDigit * 2;
lastDigit = digit;
}
return result;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Search in Rotated Sorted Array weight: 0 excerpt: feel free to try the examples seo: title: 'Search in Rotated Sorted Array' description: 'Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/description
/)
Problem:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of _O_(log _n_).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Solution:
Obviously the problem requires binary search.
The core idea of binary search is to pick the middle item and then decide to keep which half.
The precondition of it is the array must be sorted.
But take a closer look and we realize that only one of the two halves needs to be sorted. This is sufficient for us to know if the target is in that half. If not, then it must be in the other.
Whenever we choose a pivot, it must be in one of the two sorted parts of the rotated array.
- If the pivot is in the left part. We know that the begin of the left part to the pivot are sorted.
- Otherwise the pivot is in the right part. We know that the end of the right part to the pivot are sorted.
//
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
let search = function (nums, target) {
let s = 0;
let e = nums.length - 1;
while (s <= e) {
const p = ((e + s) / 2) | 0;
const pivot = nums[p];
if (pivot === target) {
return p;
}
if (pivot < nums[e]) {
// right half is sorted
if (target > pivot && target <= nums[e]) {
// target is inside the right half
s = p + 1;
} else {
e = p - 1;
}
} else {
// left half is sorted
if (target < pivot && target >= nums[s]) {
// target is inside the left half
e = p - 1;
} else {
s = p + 1;
}
}
}
return -1;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: String to Integer (atoi) weight: 0 excerpt: feel free to try the examples seo: title: 'String to Integer (atoi)' description: 'The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/description
/)
Problem:
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [â231, 231 â 1]. If the numerical value is out of the range of representable values, INT_MAX (231 â 1) or INT_MIN (â231) is returned.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (â231) is returned.
Solution:
ONE
//
/**
* @param {string} str
* @return {number}
*/
let myAtoi = function (str) {
return Math.min(2147483647, Math.max(-2147483648, parseInt(str))) || 0;
};
TWO
Looks like Number() is faster than parseInt().
//
/**
* @param {string} str
* @return {number}
*/
let myAtoi = function (str) {
return Math.min(2147483647, Math.max(-2147483648, (/^ *[-+]?\d+/.exec(str) || [0])[0]));
};
THREE
General solution.
//
/**
* @param {string} str
* @return {number}
*/
let myAtoi = function (str) {
let sign = 1;
let i = 0;
while (i < str.length) {
const cc = str.charCodeAt(i++);
if (cc === 45) {
// -
sign = -1;
break;
} else if (cc === 43) {
// +
break;
} else if (cc >= 48 && cc <= 57) {
// 0-9
i--;
break;
} else if (cc !== 32) {
// space
return 0;
}
}
let result = 0;
while (i < str.length) {
const digit = str.charCodeAt(i++) - 48;
if (digit < 0 || digit > 9) {
break;
}
result = result * 10 + digit;
}
return Math.min(2147483647, Math.max(-2147483648, result * sign));
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Valid Parentheses weight: 0 excerpt: feel free to try the examples seo: title: 'Valid Parentheses' description: 'determine if the input string is valid.' robots: [] extra: [] type: stackbit_page_meta
template: docs
[20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description
/)
Problem:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Solution:
Stack 101.
Whenever we meet a close bracket, we want to compare it to the last open bracket.
That is why we use stack to store open brackets: first in, last out.
And since there is only bracket characters, the last open bracket happens to be the last character.
//
/**
* @param {string} s
* @return {boolean}
*/
let isValid = function (s) {
const stack = [];
const pairs = {
'}': '{',
']': '[',
')': '('
};
for (const c of s) {
const open = pairs[c];
if (open) {
if (stack.pop() !== open) {
return false;
}
} else {
stack.push(c);
}
}
return stack.length <= 0;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: ZigZag Conversion weight: 0 excerpt: feel free to try the examples seo: title: 'ZigZag Conversion' description: 'The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this' robots: [] extra: [] type: stackbit_page_meta
template: docs
[6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/description
/)
Problem:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Solution:
Squeeze the zigzag pattern horizontally to form a matrix. Now deal with the odd and even columns respectively.
For example let numRows be 5, if we list out the indecies:
row
1 00 08 16
2 01 07 09 15 17
3 02 06 10 14 18
4 03 05 11 13 19
5 04 12 20
First calculate the matrix width:
pairs = floor( len(s) / (numRows + numRows - 2) )
width = pairs * 2 + ceil( (len(s) - pairs * (numRows + numRows - 2)) / numRows )
We can easily make a observation that the direction of odd and even columns and different.
Let the first column be index 0 and let i be the current position at column col.
We need to count the items between matrix[row][col] and matrix[row][col+1], exclusive.
next_i = i + (numRows - row) + (numRows - row), if col is even && 1 < row < numRows
next_i = i + row - 2 + row, if col is odd && 1 < row < numRows
If row == 1 or row == numRows, skip the odd columns.
next_i = i + numRows + (numRows - 2), if col is even && (row == 1 || row == numRows)
//
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
let convert = function (s, numRows) {
if (numRows <= 1) {
return s;
}
const pairs = Math.floor(s.length / (numRows + numRows - 2));
const width = pairs * 2 + Math.ceil((s.length - pairs * (numRows + numRows - 2)) / numRows);
let result = '';
for (let row = 1; row <= numRows; row++) {
let i = row - 1;
result += s[i] || '';
for (let col = 0; col < width; col++) {
if (row === 1 || row === numRows) {
if (col % 2 === 0) {
i += numRows + (numRows - 2);
} else {
continue;
}
} else {
if (col % 2 === 0) {
i += numRows - row + (numRows - row);
} else {
i += row - 2 + row;
}
}
result += s[i] || '';
}
}
return result;
};
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
â: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:ââ: .ïœĄ. o(â§âœâŠ)o .ïœĄ.:â
title: Math.abs() weight: 0 excerpt: seo: title: 'Math.abs()' description: '' robots: [] extra: [] type: stackbit_page_meta
template: docs
Math.abs()
The Math.abs() function returns the absolute value of a number. That is, it returns x if x is positive or zero, and the negation of x if x is negative.
Syntax
var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]];
varnameN
Variable name. It can be any legal identifier.
valueN Optional
Initial value of the variable. It can be any legal expression. Default value is undefined.
Alternatively, the Destructuring Assignment syntax can also be used to declare variables.
var { bar } = foo; // where foo = { bar:10, baz:12 };
/* This creates a variable with the name 'bar', which has a value of 10 */
Examples
Declaring and initializing two variables
var a = 0, b = 0;
Assigning two variables with single string value
var a = 'A';
var b = a;
// ...is equivalent to:
var a, b = a = 'A';
Be mindful of the order:
var x = y, y = 'A';
console.log(x + y); // undefinedA
Here, x and y are declared before any code is executed, but the assignments occur later. At the time "x = y" is evaluated, y exists so no ReferenceError is thrown and its value is undefined. So, x is assigned the undefined value. Then, y is assigned the value 'A'. Consequently, after the first line, x === undefined && y === 'A', hence the result.
Initialization of several variables
var x = 0;
function f() {
var x = y = 1; // Declares x locally; declares y globally.
}
f();
console.log(x, y); // 0 1
// In non-strict mode:
// x is the global one as expected;
// y is leaked outside of the function, though!
The same example as above but with a strict mode:
'use strict';
var x = 0;
function f() {
var x = y = 1; // Throws a ReferenceError in strict mode.
}
f();
console.log(x, y);
Implicit globals and outer function scope
Variables that appear to be implicit globals may be references to variables in an outer function scope:
var x = 0; // Declares x within file scope, then assigns it a value of 0.
console.log(typeof z); // "undefined", since z doesn't exist yet
function a() {
var y = 2; // Declares y within scope of function a, then assigns it a value of 2.
console.log(x, y); // 0 2
function b() {
x = 3; // Assigns 3 to existing file scoped x.
y = 4; // Assigns 4 to existing outer y.
z = 5; // Creates a new global variable z, and assigns it a value of 5.
// (Throws a ReferenceError in strict mode.)
}
b(); // Creates z as a global variable.
console.log(x, y, z); // 3 4 5
}
a(); // Also calls b.
console.log(x, z); // 3 5
console.log(typeof y); // "undefined", as y is local to function a
title: Javascript Variables weight: 0 excerpt: Variables can be declared without an initial value. seo: title: 'Javascript Variables' description: 'variables in the javascript language' robots: [] extra: []
template: docs
Variables are declared with the var keyword. JavaScript is
dynamically typed so every variable can hold a value of any data type.
Variables can be declared without an initial value.
Some example declarations:
//
var foo;
var bar = 42;
var foo, bar, baz;
var foo = 42,
bar = 'baz',
z;
Variables that don't explicitly get assigned an initial value have the value
undefined.
let and const can be used in addition to var. We will learn
how they differ from var later. For now, lets have a look how const differs
from var or let: const can be assigned a value only once (constant).Reassigning a value will either throw an error (in strict mode, see below) or is silently ignored:
js
//
const foo = 42;
foo = 21; // error or ignored
consts must be initialized with a value:
js
//
const foo; // error
foo = 42;
[Including keyboard users](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#including_keyboard_users 'Permalink to Including keyboard users
')
At this point, we've accomplished all of the features we set out to implement. A user can add a new task, check and uncheck tasks, delete tasks, or edit task names. And they can filter their task list by all, active, or completed tasks.
Or, at least: they can do all of these things with a mouse. Unfortunately, these features are not very accessible to keyboard-only users. Let's explore this now.
[Exploring the keyboard usability problem](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#exploring_the_keyboard_usability_problem 'Permalink to Exploring the keyboard usability problem
')
Start by clicking on the input at the top of our app, as if you're going to add a new task. You'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element. Press the Tab key, and you will see the outline appear around the "Add" button beneath the input. This shows you that the browser's focus has moved.
Press Tab a few more times, and you will see this dashed focus indicator move between each of the filter buttons. Keep going until the focus indicator is around the first "Edit" button. Press Enter.
The <Todo /> component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task.
But where did our focus indicator go?
When we switch between templates in our <Todo /> component, we completely remove the elements that were there before to replace them with something else. That means the element that we were focused on vanishes, and nothing is in focus at all. This could confuse a wide variety of users â particularly users who rely on the keyboard, or users who use a screen reader.
To improve the experience for keyboard and screen-reader users, we should manage the browser's focus ourselves.
[Focusing between templates](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#focusing_between_templates 'Permalink to Focusing between templates
')
When a user toggles a <Todo/> template from viewing to editing, we should focus on the <input> used to rename it; when they toggle back from editing to viewing, we should move focus back to the "Edit" button.
Targeting our elements
In order to focus on an element in our DOM, we need to tell React which element we want to focus on and how to find it. React's useRef hook creates an object with a single property: current. This property can be a reference to anything we want and look that reference up later. It's particularly useful for referring to DOM elements.
Change the import statement at the top of Todo.js so that it includes useRef:
import React, { useRef, useState } from "react";
Then, create two new constants beneath the hooks in your Todo() function. Each should be a ref - one for the "Edit" button in the view template and one for the edit field in the editing template.
const editFieldRef = useRef(null);
const editButtonRef = useRef(null);
These refs have a default value of null because they will not have value until we attach them to their respective elements. To do that, we'll add an attribute of ref to each element, and set their values to the appropriately named ref objects.
The textbox <input> in your editing template should be updated like this:
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
ref={editFieldRef}
/>
The "Edit" button in your view template should read like this:
<button
type="button"
className="btn"
onClick={() => setEditing(true)}
ref={editButtonRef}
>
Edit <span className="visually-hidden">{props.name}</span>
</button>
Focusing on our refs with useEffect
To use our refs for their intended purpose, we need to import another React hook: useEffect(). useEffect() is so named because it runs after React renders a given component, and will run any side-effects that we'd like to add to the render process, which we can't run inside the main function body. useEffect() is useful in the current situation because we cannot focus on an element until after the <Todo /> component renders and React knows where our refs are.
Change the import statement of Todo.js again to add useEffect:
import React, { useEffect, useRef, useState } from "react";
useEffect() takes a function as an argument; this function is executed after the component renders. Let's see this in action; put the following useEffect() call just above the return statement in the body of Todo(), and pass into it a function that logs the words "side effect" to your console:
useEffect(() => {
console.log("side effect");
});
To illustrate the difference between the main render process and code run inside useEffect(), add another log - put this one below the previous addition:
console.log("main render");
Now, open the app in your browser. You should see both messages in your console, with each one repeating three times. Note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code.
main render (3) Todo.js:100
side effect (3) Todo.js:98
That's it for our experimentation for now. Delete console.log("main render") now, and lets move on to implementing our focus management.
Focusing on our editing field
Now that we know our useEffect() hook works, we can manage focus with it. As a reminder, we want to focus on the editing field when we switch to the editing template.
Update your existing useEffect() hook so that it reads like this:
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
}
}, [isEditing]);
These changes make it so that, if isEditing is true, React reads the current value of the editFieldRef and moves browser focus to it. We also pass an array into useEffect() as a second argument. This array is a list of values useEffect() should depend on. With these values included, useEffect() will only run when one of those values changes. We only want to change focus when the value of isEditing changes.
Try it now, and you'll see that when you click an "Edit" button, focus moves to the corresponding edit <input>!
Moving focus back to the edit button
At first glance, getting React to move focus back to our "Edit" button when the edit is saved or cancelled appears deceptively easy. Surely we could add a condition to our useEffect to focus on the edit button if isEditing is false? Let's try it now â update your useEffect() call like so:
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
} else {
editButtonRef.current.focus();
}
}, [isEditing]);
This kind of mostly works. Head back to your browser and you'll see that your focus moves between Edit <input> and "Edit" button as you start and end an edit. However, you may have noticed a new problem â the "Edit" button in the final <Todo /> component is focussed immediately on page load, before we even interact with the app!
Our useEffect() hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that isEditing is false, and focuses the "Edit" button. Because there are three instances of <Todo />, we see focus on the last "Edit" button.
We need to refactor our approach so that focus changes only when isEditing changes from one value to another.
[More robust focus management](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#more_robust_focus_management 'Permalink to More robust focus management
')
In order to meet our refined criteria, we need to know not just the value of isEditing, but also when that value has changed. In order to do that, we need to be able to read the previous value of the isEditing constant. Using pseudocode, our logic should be something like this:
if (wasNotEditingBefore && isEditingNow) {
focusOnEditField()
}
if (wasEditingBefore && isNotEditingNow) {
focusOnEditButton()
}
The React team had discussed ways to get a component's previous state, and has provided an example custom hook we can use for the job.
Paste the following code near the top of Todo.js, above your Todo() function.
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
Now we'll define a wasEditing constant beneath the hooks at the top of Todo(). We want this constant to track the previous value of isEditing, so we call usePrevious with isEditing as an argument:
const wasEditing = usePrevious(isEditing);
With this constant, we can update our useEffect() hook to implement the pseudocode we discussed before â update it as follows:
useEffect(() => {
if (!wasEditing && isEditing) {
editFieldRef.current.focus();
}
if (wasEditing && !isEditing) {
editButtonRef.current.focus();
}
}, [wasEditing, isEditing]);
Note that the logic of useEffect() now depends on wasEditing, so we provide it in the array of dependencies.
Again try using the "Edit" and "Cancel" buttons to toggle between the templates of your <Todo /> component; you'll see the browser focus indicator move appropriately, without the problem we discussed at the start of this section.
[Focusing when the user deletes a task](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#focusing_when_the_user_deletes_a_task 'Permalink to Focusing when the user deletes a task
')
There's one last keyboard experience gap: when a user deletes a task from the list, the focus vanishes. We're going to follow a pattern similar to our previous changes: we'll make a new ref, and utilize our usePrevious() hook, so that we can focus on the list heading whenever a user deletes a task.
Why the list heading?
Sometimes, the place we want to send our focus to is obvious: when we toggled our <Todo /> templates, we had an origin point to "go back" to â the "Edit" button. In this case however, since we're completely removing elements from the DOM, we have no place to go back to. The next best thing is an intuitive location somewhere nearby. The list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left.
Creating our ref
Import the useRef() and useEffect() hooks into App.js â you'll need them both below:
import React, { useState, useRef, useEffect } from "react";
Then declare a new ref inside the App() function. Just above the return statement is a good place:
const listHeadingRef = useRef(null);
Prepare the heading
Heading elements like our <h2> are not usually focusable. This isn't a problem â we can make any element programmatically focusable by adding the attribute tabindex="-1" to it. This means only focusable with JavaScript. You can't press Tab to focus on an element with a tabindex of -1 the same way you could do with a <button> or <a> element (this can be done using tabindex="0", but that's not really appropriate in this case).
Let's add the tabindex attribute â written as tabIndex in JSX â to the heading above our list of tasks, along with our headingRef:
<h2 id="list-heading" tabIndex="-1" ref={listHeadingRef}>
{headingText}
</h2>
Note: The tabindex attribute is great for accessibility edge-cases, but you should take great care to not overuse it. Only apply a tabindex to an element when you're absolutely sure that making it focusable will benefit your user in some way. In most cases, you should be utilizing elements that can naturally take focus, such as buttons, anchors, and inputs. Irresponsible usage of tabindex could have a profoundly negative impact on keyboard and screen-reader users!
Getting previous state
We want to focus on the element associated with our ref (via the ref attribute) only when our user deletes a task from their list. That's going to require the usePrevious() hook we already used earlier on. Add it to the top of your App.js file, just below the imports:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
Now add the following, above the return statement inside the App() function:
const prevTaskLength = usePrevious(tasks.length);
Here we are invoking usePrevious() to track the length of the tasks state, like so:
Note: Since we're now utilizing usePrevious() in two files, a good efficiency refactor would be to move the usePrevious() function into its own file, export it from that file, and import it where you need it. Try doing this as an exercise once you've got to the end.
Using useEffect() to control our heading focus
Now that we've stored how many tasks we previously had, we can set up a useEffect() hook to run when our number of tasks changes, which will focus the heading if the number of tasks we have now is less than with it previously was â i.e. we deleted a task!
Add the following into the body of your App() function, just below your previous additions:
useEffect(() => {
if (tasks.length - prevTaskLength === -1) {
listHeadingRef.current.focus();
}
}, [tasks.length, prevTaskLength]);
We only try to focus on our list heading if we have fewer tasks now than we did before. The dependencies passed into this hook ensure it will only try to re-run when either of those values (the number of current tasks, or the number of previous tasks) changes.
Now, when you delete a task in your browser, you will see our dashed focus outline appear around the heading above the list.
[Finished!](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility#finished! 'Permalink to Finished
!')
You've just finished building a React app from the ground up! Congratulations! The skills you've learned here will be a great foundation to build on as you continue working with React.
Most of the time, you can be an effective contributor to a React project even if all you do is think carefully about components and their state and props. Remember to always write the best HTML you can.
useRef() and useEffect() are somewhat advanced features, and you should be proud of yourself for using them! Look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users. Remember: our app would have been inaccessible to keyboard users without them!
title: Accessibility template: post subtitle: Our products should be accessible to all excerpt: Making our products accessible benefits everyone, not just people with disabilities date: 2022-05-29T17:38:20.581Z image: https://www.esri.com/arcgis-blog/wp-content/uploads/2020/07/building-web-accessibility-barriers-guidelines-standards_01.jpg thumb_image: https://www.esri.com/arcgis-blog/wp-content/uploads/2020/07/building-web-accessibility-barriers-guidelines-standards_01.jpg image_position: right author: src/data/authors/backup.yaml categories:
- src/data/categories/css.yaml
- src/data/categories/html.yaml
- src/data/categories/javascript.yaml
tags:
- src/data/tags/career.yaml
- src/data/tags/javascript.yaml
show_author_bio: true related_posts:
- src/pages/blog/awesome-resources.md
- src/pages/blog/adding-css-to-your-html.md
cmseditable: true
Accessibility is everyoneâs responsibility, and the purpose of this document is to provide general accessibility guidelines to developers and designers.
Overview
Our products should be accessible to all. At minimum, features should comply to the requirements listed in 508 Reference Guide - 1194.22 from the US Access Board, and conform to Web Content Accessibility Guidelines 2.0 at Level AA.
Making our products accessible benefits everyone, not just people with disabilities. Below are some examples of use cases in which accessibility is important:
Visual: blindness, low vision, color blindness, using a screen reader or related assistive tech for lifestyle reasons (e.g. long car commute), machine readability and screen scraping technologies
Hearing: deafness, hearing impairment, speech impairment, using closed captioning or other assistive features for lifestyle reasons (e.g. coworking in a loud coffee shop)
Cognitive: including short-term memory issues, dyslexia, learning disabilities, trying to work or consume content while distracted or multitasking, etc.
Mobility: mobility impairments, repetitive stress injuries, power users who love keyboard shortcuts, busy parents holding a sleeping child while trying to operate a computer with one hand, etc.
General guidelines
Semantic markup
Always use semantic HTML elements, like button, ul, nav. Most modern browsers implement the accessibility features outlined in the specs for these elements; without them, elements will need additional ARIA attributes and roles to be recognized by assistive technologies.
Elements like h1-h6, nav, footer, header have meaningful roles assigned, so use them carefully. This can help assistive technologies read the page better and help users find information quicker.
Only use a div or a span to markup up content when there isn't another HTML element that would semantically be more appropriate, or when an element is needed exclusively for applying CSS styles or JS behaviors.
<!-- Do: Button can be focused and tabbed to. -->
<button type="button" class="btn">Send</button>
<!-- Don't: Button can't be focused and tabbed to. -->
<span class="btn">Send</span>
More on semantic markup:
Keyboard accessibility
Make sure elements can be reached via tabbing, and actions can be triggered with a keyboard. Using semantic markup is especially important in this case as it ensures that actionable elements are tabbable and triggerable without a mouse. Note that elements positioned off-screen are still tabbable, but those hidden with display: none or visibility: hidden are effectively removed from content since they are neither read by screen readers nor reachable by keyboard.
Tab order is determined by the order of elements in the DOM, and not by their visual positioning on the page after CSS is applied. CSS properties float and order for flex items are two common sources for disconnection between visual and DOM order.
The tabindex attribute should only be used when absolutely necessary.
tabindex=0/-1makes an element focusable, whiletabindex=0also includes the element in the normal tab order. In both cases, keyboard triggers of the element still require scripting, so where possible, use interactive content instead.tabindex=1+takes an element to the very front of the default tab order. When it's applied, the element's visual positioning is no longer indicative of its tab order, and the only way to find out where an element is would be by tabbing through the page. Therefore, unless a page is carefully designed around elements with positive tabindex, it is very error-proned, and thus currently prohibited in github.com.
Finally, bear in mind that some assistive technologies have keyboard combinations of their own that will override the combination on the web page, so don't rely on keyboard shortcuts as the only alternative to mouse actions.
<!-- Do: Tab order can be guessed. -->
<button type="button" class="btn">1</button>
<button type="button" class="btn">2</button>
<button type="button" class="btn">3</button>
<!-- Don't: The second button's tab order is unexpected. -->
<button type="button" class="btn">1</button>
<button type="button" class="btn" tabindex="1">2</button>
<button type="button" class="btn">3</button>
More on keyboard accessibility:
Visual accessibility
Be mindful when using small font size, thin font weight, low contrast colors in designs as it can severely affect usability.
Instead of relying solely on color to communicate information, always combine color with another factor, like shape or position change. This is important because some colors can be hard to tell apart due to color blindness or weak eyesight.
More on visual accessibility:
Text and labels
Make sure text-based alternative is always available when using icons, images, and graphs, and that the text by itself presents meaningful information.
<!-- Do: Link text communicates destination. -->
<p>Find out more about <a href="#url">GitHub Enterprise pricing</a>.<br /></p>
<!-- Don't: "Click here" is not meaningful. -->
<p>
To find out more about GitHub Enterprise pricing,
<a href="#url">click here</a>.
</p>
Use aria-label when there is no text.
<a href="https://help.github.com/"><%= octicon("question", :"aria-label" => "Help") %></a>
Link responsibly
Navigating from a list of all the links on a given web page is very common for assistive technology users. We should make sure that the link text itself is meaningful and unique, and there should be as few duplicated references as possible.
More on link responsibly:
Dynamic content
When using JavaScript to change the content on the page, always make sure that screen reader users are informed about the change. This can be done with aria-live, or focus management.
More on dynamic content:
Focus management
Focus management is useful for informing users about updated content, and for making sure users land on the next useful section after performing an action. This means using scripts to change userâs currently focused element, and when focus changes, screen readers will read out change.
Accessible forms
It is common for assistive technology users to jump straight to a form when using a website, so make sure most relevant information is in the form and is labelled properly. Labels and inputs should be associated with the label[for] and input[id], and help texts should either be part of the label or be associated with aria-describedby.
<!-- Do: Click "Email" label to focus on the input, and help text is read out by screen readers when focusing on the input. -->
<label for="test_input">Email</label><br />
<input id="test_input" aria-describedby="test_input_help_good" class="width-full my-1" type="email" />
<div id="test_input_help_good" class="f6">Please enter an email ending with @github.com.</div>
<!-- Don't: Input and label are not associated, and help text is not read out by screen reader when focusing on the input. -->
<label>Email</label><br />
<input type="email" class="width-full my-1" />
<div id="test_input_help_bad" class="f6">Please enter an email ending with @github.com.</div>
Development tools
Linting
We currently run basic linting against positive tabindex and anchor links with href="#".
We do client side scanning of inaccessible elements in development environment. The inaccessible elements will be styled with red borders with an onclick alert and console warnings.
External tools
Google Chrome provides an Accessibility Developer Tools extension. Once installed, go to Audits tab in developer tools, tick Accessibility. It scans the page for violations and suggests solutions.
If you're working on a design that uses color to communicate something, grab the Chromatic Vision Simulator app, this will let you use your iPhone camera to see what a colorblind person would see.
Check out the Web Accessibility showcase on GitHub. GitHubbers are free to add more projects to the showcase.
Manual testing
Screen reader
To use VoiceOver, the built-in screen reader for Mac, just hit â + F5. This will start voice narration and display most of the spoken information in a text box.
Use alt + control + left/right to navigate a web page. alt + control + space to click on an element. For more help with VoiceOver, check out the built-in tutorial in System Preferences > Accessibility > VoiceOver > Open VoiceOver Training.
Keep in mind that behaviors in different screen readers can differ when navigating the same web page; just like designing for different browsers, when it comes to accessibility, it is not just the implementation of the browsers that can be different, but also the ones of assistive softwares.
Internal resources
You can mention these teams when looking for help:
@github/accessibility: GitHubbers interested in accessibility related topics and work on website accessibility issues.
@github/colorblind: GitHubbers who are interested in accessibility for colorblindness.
Go to #accessibility Slack channel to ask questions or discuss accessibility issues.
- Check github/accessibility repository for information on events or learning resources.
User support
Accessibility is a priority for us, if you ever encounter accessibility related issues when using github.com, please donât hesitate to reach out to us via the contact page or email us at support@github.com, we will try our best to assist.
For information about the accessibility compliance of GitHub products, please refer to our VPAT report, outlining §508 accessibility information for GitHub.com, GitHub Enterprise, and GitHub Desktop.
title: Math.acos() weight: 0 excerpt: seo: title: ' Math.acos()' description: '' robots: [] extra: [] type: stackbit_page_meta
template: docs
Math.acos()
The Math.acos() function returns the arccosine (in radians) of a number, that is
âxâââ[â
ââ
1;â1],â
Math.acosâ(`x) `â=âarccosâ(_x_)â=âthe uniqueâ
yâââ[0;âÏ]âsuch thatâ
cosâ(_y_)â=âx
Polyfill
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: https://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// « accumulator, kValue, k, O »).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
}
});
}
Note: If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable.
Data structures in JavaScript
Here's a website I created to practice data structures! directory Edit descriptionds-algo-official-c3dw6uapg-bgoonz.vercel.app
Here's the repo that the website is built on: bgoonz/DS-ALGO-OFFICIAL Navigation ####Author:Bryan Guner Big O notation is the language we use for talking about how long an algorithm takesâŠgithub.com
Resources (article content below
):
- Abdul Bari: YouTubeChannel for Algorithms
- Data Structures and algorithms
- Data Structures and algorithms Course
- Khan Academy
- Data structures by mycodeschoolPre-requisite for this lesson is good understanding of pointers in C.
- MIT 6.006: Intro to Algorithms(2011)
- Data Structures and Algorithms by Codewithharry
- Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein
- Competitive Programming 3 by Steven Halim and Felix Halim
- Competitive Programmers Hand Book Beginner friendly hand book for competitive programmers.
- Data Structures and Algorithms Made Easy by Narasimha Karumanchi
- Learning Algorithms Through Programming and Puzzle Solving by Alexander Kulikov and Pavel Pevzner
- LeetCode
- InterviewBit
- Codility
- HackerRank
- Project Euler
- Spoj
- Google Code Jam practice problems
- HackerEarth
- Top Coder
- CodeChef
- Codewars
- CodeSignal
- CodeKata
- Firecode
- Master the Coding Interview: Big Tech (FAANG) Interviews Course by Andrei and his team.
- Common Python Data Structures Data structures are the fundamental constructs around which you build your programs. Each data structure provides a particular way of organizing data so it can be accessed efficiently, depending on your use case. Python ships with an extensive set of data structures in its standard library.
- Fork CPP A good course for beginners.
- EDU Advanced course.
- C++ For Programmers Learn features and constructs for C++.
- GeeksForGeeks â A CS portal for geeks
- Learneroo â Algorithms
- Top Coder tutorials
- Infoarena training path (RO)
- Steven & Felix Halim â Increasing the Lower Bound of Programming Contests (UVA Online Judge)--- title: Data Structures In Python template: docs excerpt: In this tutorial, you'll learn about Python's data structures. You'll look at several implementations of abstract data types and learn which implementations are best for your specific use cases.
Common Python Data Structures (Guide) â Real Python
**_space_
**
The space complexity represents the memory consumption of a data structure. As for most of the things in life, you can't have it all, so it is with the data structures. You will generally need to trade some time for space or the other way around.
_time_
The time complexity for a data structure is in general more diverse than its space complexity.
_Several operations_
In contrary to algorithms, when you look at the time complexity for data structures you need to express it for several operations that you can do with data structures. It can be adding elements, deleting elements, accessing an element or even searching for an element.
_Dependent on data_
Something that data structure and algorithms have in common when talking about time complexity is that they are both dealing with data. When you deal with data you become dependent on them and as a result the time complexity is also dependent of the data that you received. To solve this problem we talk about 3 different time complexity.
- The best-case complexity: when the data looks the best -
The worst-case complexity: when the data looks the worst
The average-case complexity: when the data looks average
Big O notation
The complexity is usually expressed with the Big O notation. The wikipedia page about this subject is pretty complex but you can find here a good summary of the different complexity for the most famous data structures and sorting algorithms.
The Array data structure

Definition
A Queue is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal operations are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the Queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the Queue will be the first one to be removed. From Wikipedia>)
As for the Stack data structure, a peek operation is often added to the Queue data structure. It returns the value of the front element without dequeuing it.
2. Objects
Think of objects as a logical grouping of a bunch of properties.
Properties could be some variable that it's storing or some methods that it's using.
I also visualize an object as a table.
The main difference is that object's "index" need not be numbers and is not necessarily sequenced.

//
// 16. Creating an Object
let newObj = {
name: "I'm an object",
values: [1, 10, 11, 20],
others: '',
'1property': 'example of property name starting with digit'
};
// 17. Figure out what keys/properties are in an object
console.log(Object.keys(newObj));
// Results: [ 'name', 'values', 'others', '1property' ]
// 18. Show all values stored in the object
console.log(Object.values(newObj));
// Results:
// [ 'I\'m an object',
// [ 1, 10, 11, 20 ],
// '',
// 'example of property name starting with digit' ]
// 19. Show all key and values of the object
for (let [key, value] of Object.entries(newObj)) {
console.log(`${key}: ${value}`);
}
// Results:
// name: I'm an object
// values: 1,10,11,20
// others:
// 1property: example of property name starting with digit
// 20. Accessing Object's Properties
// Two different ways to access properties, both produce same results
console.log(newObj.name);
console.log(newObj['name']);
// But if the property name starts with a digit,
// we CANNOT use dot notation
console.log(newObj['1property']);
// 21. Adding a Method to an Object
newObj.helloWorld = function () {
console.log('Hello World from inside an object!');
};
// 22. Invoking an Object's Method
newObj.helloWorld();
The Hash Table

_Definition_
A Graph data structure consists of a finite (and possibly mutable) set of vertices or nodes or points, together with a set of unordered pairs of these vertices for an undirected Graph or a set of ordered pairs for a directed Graph. These pairs are known as edges, arcs, or lines for an undirected Graph and as arrows, directed edges, directed arcs, or directed lines for a directed Graph. The vertices may be part of the Graph structure, or may be external entities represented by integer indices or references. From Wikipedia
A Graph data structure may also associate to each edge some edge value, such as a symbolic label or a numeric attribute (cost, capacity, length, etc.).
Representation There are different ways of representing a graph, each of them with its own advantages and disadvantages. Here are the main 2:
Adjacency list: For every vertex a list of adjacent vertices is stored. This can be viewed as storing the list of edges. This data structure allows the storage of additional data on the vertices and edges. Adjacency matrix: Data are stored in a two-dimensional matrix, in which the rows represent source vertices and columns represent destination vertices. The data on the edges and vertices must be stored externally. Complexity Adjacency list Storage Add Vertex Add Edge Query O( V + E Adjacency matrix Storage Add Vertex Add Edge Query O( V ^2) O(
Graph
The code
//below uses the adjacency list representation.
//
function Graph() {
this.vertices = [];
this.edges = [];
this.numberOfEdges = 0;
}
Graph.prototype.addVertex = function(vertex) {
this.vertices.push(vertex);
this.edges[vertex] = [];
};
Graph.prototype.removeVertex = function(vertex) {
let index = this.vertices.indexOf(vertex);
if(~index) {
this.vertices.splice(index, 1);
}
while(this.edges[vertex].length) {
let adjacentVertex = this.edges[vertex].pop();
this.removeEdge(adjacentVertex, vertex);
}
};
Graph.prototype.addEdge = function(vertex1, vertex2) {
this.edges[vertex1].push(vertex2);
this.edges[vertex2].push(vertex1);
this.numberOfEdges++;
};
Graph.prototype.removeEdge = function(vertex1, vertex2) {
let index1 = this.edges[vertex1] ? this.edges[vertex1].indexOf(vertex2) : -1;
let index2 = this.edges[vertex2] ? this.edges[vertex2].indexOf(vertex1) : -1;
if(~index1) {
this.edges[vertex1].splice(index1, 1);
this.numberOfEdges--;
}
if(~index2) {
this.edges[vertex2].splice(index2, 1);
}
};
Graph.prototype.size = function() {
return this.vertices.length;
};
Graph.prototype.relations = function() {
return this.numberOfEdges;
};
Graph.prototype.traverseDFS = function(vertex, fn) {
if(!~this.vertices.indexOf(vertex)) {
return console.log('Vertex not found');
}
let visited = [];
this._traverseDFS(vertex, visited, fn);
};
Graph.prototype._traverseDFS = function(vertex, visited, fn) {
visited[vertex] = true;
if(this.edges[vertex] !== undefined) {
fn(vertex);
}
for(let i = 0; i < this.edges[vertex].length; i++) {
if(!visited[this.edges[vertex][i]]) {
this._traverseDFS(this.edges[vertex][i], visited, fn);
}
}
};
Graph.prototype.traverseBFS = function(vertex, fn) {
if(!~this.vertices.indexOf(vertex)) {
return console.log('Vertex not found');
}
let queue = [];
queue.push(vertex);
let visited = [];
visited[vertex] = true;
while(queue.length) {
vertex = queue.shift();
fn(vertex);
for(let i = 0; i < this.edges[vertex].length; i++) {
if(!visited[this.edges[vertex][i]]) {
visited[this.edges[vertex][i]] = true;
queue.push(this.edges[vertex][i]);
}
}
}
};
Graph.prototype.pathFromTo = function(vertexSource, vertexDestination) {
if(!~this.vertices.indexOf(vertexSource)) {
return console.log('Vertex not found');
}
let queue = [];
queue.push(vertexSource);
let visited = [];
visited[vertexSource] = true;
let paths = [];
while(queue.length) {
let vertex = queue.shift();
for(let i = 0; i < this.edges[vertex].length; i++) {
if(!visited[this.edges[vertex][i]]) {
visited[this.edges[vertex][i]] = true;
queue.push(this.edges[vertex][i]);
// save paths between vertices
paths[this.edges[vertex][i]] = vertex;
}
}
}
if(!visited[vertexDestination]) {
return undefined;
}
let path = [];
for(let j = vertexDestination; j != vertexSource; j = paths[j]) {
path.push(j);
}
path.push(j);
return path.reverse().join('-');
};
Graph.prototype.print = function() {
console.log(this.vertices.map(function(vertex) {
return (vertex + ' -> ' + this.edges[vertex].join(', ')).trim();
}, this).join(' | '));
};
let graph = new Graph();
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
graph.addVertex(5);
graph.addVertex(6);
graph.print(); // 1 -> | 2 -> | 3 -> | 4 -> | 5 -> | 6 ->
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 3);
graph.addEdge(2, 5);
graph.addEdge(3, 4);
graph.addEdge(4, 5);
graph.addEdge(4, 6);
graph.print(); // 1 -> 2, 5 | 2 -> 1, 3, 5 | 3 -> 2, 4 | 4 -> 3, 5, 6 | 5 -> 1, 2, 4 | 6 -> 4
console.log('graph size (number of vertices):', graph.size()); // => 6
console.log('graph relations (number of edges):', graph.relations()); // => 7
graph.traverseDFS(1, function(vertex) { console.log(vertex); }); // => 1 2 3 4 5 6
console.log('---');
graph.traverseBFS(1, function(vertex) { console.log(vertex); }); // => 1 2 5 3 4 6
graph.traverseDFS(0, function(vertex) { console.log(vertex); }); // => 'Vertex not found'
graph.traverseBFS(0, function(vertex) { console.log(vertex); }); // => 'Vertex not found'
console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1
console.log('path from 3 to 5:', graph.pathFromTo(3, 5)); // => 3-2-5
graph.removeEdge(1, 2);
graph.removeEdge(4, 5);
graph.removeEdge(10, 11);
console.log('graph relations (number of edges):', graph.relations()); // => 5
console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-5-1
graph.addEdge(1, 2);
graph.addEdge(4, 5);
console.log('graph relations (number of edges):', graph.relations()); // => 7
console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1
graph.removeVertex(5);
console.log('graph size (number of vertices):', graph.size()); // => 5
console.log('graph relations (number of edges):', graph.relations()); // => 4
console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-1
`
title: All Emojis weight: 0 excerpt: All Emojis seo: title: '' description: '' robots: [] extra: []
template: docs
The Set
Sets
Sets are pretty much what it sounds like. It's the same intuition as Set in Mathematics. I visualize Sets as Venn Diagrams.
//
// 23. Creating a new Set
let newSet = new Set();
// 24. Adding new elements to a set
newSet.add(1); // Set[1]
newSet.add('text'); // Set[1, "text"]
// 25. Check if element is in set
newSet.has(1); // true
// 24. Check size of set
console.log(newSet.size); // Results: 2
// 26. Delete element from set
newSet.delete(1); // Set["text"]
// 27. Set Operations: isSuperSet
function isSuperset(set, subset) {
for (let elem of subset) {
if (!set.has(elem)) {
return false;
}
}
return true;
}
// 28. Set Operations: union
function union(setA, setB) {
let _union = new Set(setA);
for (let elem of setB) {
_union.add(elem);
}
return _union;
}
// 29. Set Operations: intersection
function intersection(setA, setB) {
let _intersection = new Set();
for (let elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem);
}
}
return _intersection;
}
// 30. Set Operations: symmetricDifference
function symmetricDifference(setA, setB) {
let _difference = new Set(setA);
for (let elem of setB) {
if (_difference.has(elem)) {
_difference.delete(elem);
} else {
_difference.add(elem);
}
}
return _difference;
}
// 31. Set Operations: difference
function difference(setA, setB) {
let _difference = new Set(setA);
for (let elem of setB) {
_difference.delete(elem);
}
return _difference;
}
// Examples
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3]);
let setC = new Set([3, 4, 5, 6]);
console.log(isSuperset(setA, setB)); // => true
console.log(union(setA, setC)); // => Set [1, 2, 3, 4, 5, 6]
console.log(intersection(setA, setC)); // => Set [3, 4]
console.log(symmetricDifference(setA, setC)); // => Set [1, 2, 5, 6]
console.log(difference(setA, setC)); // => Set [1, 2]
The Singly Linked List

The Doubly Linked List

The Stack

The Queue

The Tree
The Graph

All Emojis
đ đ đ đ đ đ đ đ€Ł đ„Č âșïž đ đ đ đ đ đ đ đ„° đ đ đ đ đ đ đ đ đ€Ș đ€š đ§ đ€ đ đ„ž đ€© đ„ł đ đ đ đ đ đ đ âčïž đŁ đ đ« đ© đ„ș đą đ đ€ đ đĄ đ€Ź đ€Ż đł đ„” đ„¶ đ± đš đ° đ„ đ đ€ đ€ đ€ đ€« đ€„ đ¶ đ đ đŹ đ đŻ đŠ đ§ đź đČ đ„± đŽ đ€€ đȘ đ” đ€ đ„Ž đ€ą đ€ź đ€§ đ· đ€ đ€ đ€ đ€ đ đż đč đș đ€Ą đ© đ» đ â ïž đœ đŸ đ€ đ đș đž đč đ» đŒ đœ đ đż đŸ
Gestures and Body Parts
đ đ€ đ â đ đ đ€ đ€ âïž đ€ đ€ đ€ đ€ đ đ đ đ đ âïž đ đ â đ đ€ đ€ đ đ đ đ€Č đ€ đ âïž đ đ€ł đȘ đŠŸ đŠ” đŠż đŠ¶ đŁ đ đŠ» đ đ« đ« đ§ đŠ· đŠŽ đ đ đ đ đ đ©ž
People and Fantasy
đ¶ đ§ đ§ đŠ đ© đ§ đš đ©âđŠ± đ§âđŠ± đšâđŠ± đ©â𩰠đ§â𩰠đšâ𩰠đ±ââïž đ± đ±ââïž đ©â𩳠đ§â𩳠đšâ𩳠đ©âđŠČ đ§âđŠČ đšâđŠČ đ§ đ” đ§ đŽ đČ đłââïž đł đłââïž đ§ đźââïž đź đźââïž đ·ââïž đ· đ·ââïž đââïž đ đââïž đ”ïžââïž đ”ïž đ”ïžââïž đ©ââïž đ§ââïž đšââïž đ©âđŸ đ§âđŸ đšâđŸ đ©âđł đ§âđł đšâđł đ©âđ đ§âđ đšâđ đ©âđ€ đ§âđ€ đšâđ€ đ©âđ« đ§âđ« đšâđ« đ©âđ đ§âđ đšâđ đ©âđ» đ§âđ» đšâđ» đ©âđŒ đ§âđŒ đšâđŒ đ©âđ§ đ§âđ§ đšâđ§ đ©âđŹ đ§âđŹ đšâđŹ đ©âđš đ§âđš đšâđš đ©âđ đ§âđ đšâđ đ©ââïž đ§ââïž đšââïž đ©âđ đ§âđ đšâđ đ©ââïž đ§ââïž đšââïž đ°ââïž đ° đ°ââïž đ€”ââïž đ€” đ€”ââïž đž đ€Ž đ„· đŠžââïž đŠž đŠžââïž đŠčââïž đŠč đŠčââïž đ€¶ đ§âđ đ đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đ§ââïž đ§ đ§ââïž đŒ đ€° đ€± đ©âđŒ đ§âđŒ đšâđŒ đââïž đ đââïž đââïž đ đââïž đ ââïž đ đ ââïž đââïž đ đââïž đââïž đ đââïž đ§ââïž đ§ đ§ââïž đ€Šââïž đ€Š đ€Šââïž đ€·ââïž đ€· đ€·ââïž đââïž đ đââïž đââïž đ đââïž đââïž đ đââïž đââïž đ đââïž đ§ââïž đ§ đ§ââïž đ đ€ł đ đș đŻââïž đŻ đŻââïž đŽ đ©âđŠœ đ§âđŠœ đšâđŠœ đ©âđŠŒ đ§âđŠŒ đšâđŠŒ đ¶ââïž đ¶ đ¶ââïž đ©â𩯠đ§â𩯠đšâ𩯠đ§ââïž đ§ đ§ââïž đââïž đ đââïž đ§ââïž đ§ đ§ââïž đ đ§âđ€âđ§ đŹ đ« đ©ââ€ïžâđ© đ đšââ€ïžâđš đ©ââ€ïžâđš đ©ââ€ïžâđâđ© đ đšââ€ïžâđâđš đ©ââ€ïžâđâđš đȘ đšâđ©âđŠ đšâđ©âđ§ đšâđ©âđ§âđŠ đšâđ©âđŠâđŠ đšâđ©âđ§âđ§ đšâđšâđŠ đšâđšâđ§ đšâđšâđ§âđŠ đšâđšâđŠâđŠ đšâđšâđ§âđ§ đ©âđ©âđŠ đ©âđ©âđ§ đ©âđ©âđ§âđŠ đ©âđ©âđŠâđŠ đ©âđ©âđ§âđ§ đšâđŠ đšâđŠâđŠ đšâđ§ đšâđ§âđŠ đšâđ§âđ§ đ©âđŠ đ©âđŠâđŠ đ©âđ§ đ©âđ§âđŠ đ©âđ§âđ§ đŁ đ€ đ„ đ«
Clothing and Accessories
đ§ł đ âïž đ§” đȘĄ đȘą đ§¶ đ đ¶ đ„œ đ„Œ đŠș đ đ đ đ§Ł đ§€ đ§„ đ§Š đ đ đ„» đ©Ž đ©± đ©Č 𩳠đ đ đ đ đ đ đ đ đ„Ÿ đ„ż đ đĄ đ©° đą đ đ đ© đ đ§ą â đȘ đ đ đŒ
Pale Emojis
đđ» đ€đ» đđ» âđ» đđ» đđ» đ€đ» đ€đ» âđ» đ€đ» đ€đ» đ€đ» đ€đ» đđ» đđ» đđ» đđ» đđ» âđ» đđ» đđ» âđ» đđ» đ€đ» đ€đ» đđ» đđ» đđ» đ€Čđ» đđ» âđ» đ đ» đ€łđ» đȘđ» đŠ”đ» đжđ» đđ» đŠ»đ» đđ» đ¶đ» đ§đ» đ§đ» đŠđ» đ©đ» đ§đ» đšđ» đ©đ»âđŠ± đ§đ»âđŠ± đšđ»âđŠ± đ©đ»â𩰠đ§đ»â𩰠đšđ»â𩰠đ±đ»ââïž đ±đ» đ±đ»ââïž đ©đ»â𩳠đ§đ»â𩳠đšđ»â𩳠đ©đ»âđŠČ đ§đ»âđŠČ đšđ»âđŠČ đ§đ» đ”đ» đ§đ» đŽđ» đČđ» đłđ»ââïž đłđ» đłđ»ââïž đ§đ» đźđ»ââïž đźđ» đźđ»ââïž đ·đ»ââïž đ·đ» đ·đ»ââïž đđ»ââïž đđ» đđ»ââïž đ”đ»ââïž đ”đ» đ”đ»ââïž đ©đ»ââïž đ§đ»ââïž đšđ»ââïž đ©đ»âđŸ đ§đ»âđŸ đšđ»âđŸ đ©đ»âđł đ§đ»âđł đšđ»âđł đ©đ»âđ đ§đ»âđ đšđ»âđ đ©đ»âđ€ đ§đ»âđ€ đšđ»âđ€ đ©đ»âđ« đ§đ»âđ« đšđ»âđ« đ©đ»âđ đ§đ»âđ đšđ»âđ đ©đ»âđ» đ§đ»âđ» đšđ»âđ» đ©đ»âđŒ đ§đ»âđŒ đšđ»âđŒ đ©đ»âđ§ đ§đ»âđ§ đšđ»âđ§ đ©đ»âđŹ đ§đ»âđŹ đšđ»âđŹ đ©đ»âđš đ§đ»âđš đšđ»âđš đ©đ»âđ đ§đ»âđ đšđ»âđ đ©đ»ââïž đ§đ»ââïž đšđ»ââïž đ©đ»âđ đ§đ»âđ đšđ»âđ đ©đ»ââïž đ§đ»ââïž đšđ»ââïž đ°đ»ââïž đ°đ» đ°đ»ââïž đ€”đ»ââïž đ€”đ» đ€”đ»ââïž đžđ» đ€Žđ» đ„·đ» đŠžđ»ââïž đŠžđ» đŠžđ»ââïž đŠčđ»ââïž đŠčđ» đŠčđ»ââïž đ€¶đ» đ§đ»âđ đ đ» đ§đ»ââïž đ§đ» đ§đ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đŒđ» đ€°đ» đ€±đ» đ©đ»âđŒ đ§đ»âđŒ đšđ»âđŒ đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đ đ»ââïž đ đ» đ đ»ââïž đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đ€Šđ»ââïž đ€Šđ» đ€Šđ»ââïž đ€·đ»ââïž đ€·đ» đ€·đ»ââïž đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đđ» đșđ» đŽđ» đ©đ»âđŠœ đ§đ»âđŠœ đšđ»âđŠœ đ©đ»âđŠŒ đ§đ»âđŠŒ đšđ»âđŠŒ đ¶đ»ââïž đ¶đ» đ¶đ»ââïž đ©đ»â𩯠đ§đ»â𩯠đšđ»â𩯠đ§đ»ââïž đ§đ» đ§đ»ââïž đđ»ââïž đđ» đđ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đđ» đ§đ»âđ€âđ§đ» đŹđ» đ«đ» đ§đ»ââïž đ§đ» đ§đ»ââïž đđ» đđ» đđ»ââïž đđ» đđ»ââïž đđ»ââïž đđ» đđ»ââïž đŁđ»ââïž đŁđ» đŁđ»ââïž đđ»ââïž đđ» đđ»ââïž âčđ»ââïž âčđ» âčđ»ââïž đđ»ââïž đđ» đđ»ââïž đŽđ»ââïž đŽđ» đŽđ»ââïž đ”đ»ââïž đ”đ» đ”đ»ââïž đ€žđ»ââïž đ€žđ» đ€žđ»ââïž đ€œđ»ââïž đ€œđ» đ€œđ»ââïž đ€Ÿđ»ââïž đ€Ÿđ» đ€Ÿđ»ââïž đ€čđ»ââïž đ€čđ» đ€čđ»ââïž đ§đ»ââïž đ§đ» đ§đ»ââïž đđ» đđ»
Cream White Emojis
đđŒ đ€đŒ đđŒ âđŒ đđŒ đđŒ đ€đŒ đ€đŒ âđŒ đ€đŒ đ€đŒ đ€đŒ đ€đŒ đđŒ đđŒ đđŒ đđŒ đđŒ âđŒ đđŒ đđŒ âđŒ đđŒ đ€đŒ đ€đŒ đđŒ đđŒ đđŒ đ€ČđŒ đđŒ âđŒ đ đŒ đ€łđŒ đȘđŒ đŠ”đŒ đжđŒ đđŒ đŠ»đŒ đđŒ đ¶đŒ đ§đŒ đ§đŒ đŠđŒ đ©đŒ đ§đŒ đšđŒ đ©đŒâđŠ± đ§đŒâđŠ± đšđŒâđŠ± đ©đŒâ𩰠đ§đŒâ𩰠đšđŒâ𩰠đ±đŒââïž đ±đŒ đ±đŒââïž đ©đŒâ𩳠đ§đŒâ𩳠đšđŒâ𩳠đ©đŒâđŠČ đ§đŒâđŠČ đšđŒâđŠČ đ§đŒ đ”đŒ đ§đŒ đŽđŒ đČđŒ đłđŒââïž đłđŒ đłđŒââïž đ§đŒ đźđŒââïž đźđŒ đźđŒââïž đ·đŒââïž đ·đŒ đ·đŒââïž đđŒââïž đđŒ đđŒââïž đ”đŒââïž đ”đŒ đ”đŒââïž đ©đŒââïž đ§đŒââïž đšđŒââïž đ©đŒâđŸ đ§đŒâđŸ đšđŒâđŸ đ©đŒâđł đ§đŒâđł đšđŒâđł đ©đŒâđ đ§đŒâđ đšđŒâđ đ©đŒâđ€ đ§đŒâđ€ đšđŒâđ€ đ©đŒâđ« đ§đŒâđ« đšđŒâđ« đ©đŒâđ đ§đŒâđ đšđŒâđ đ©đŒâđ» đ§đŒâđ» đšđŒâđ» đ©đŒâđŒ đ§đŒâđŒ đšđŒâđŒ đ©đŒâđ§ đ§đŒâđ§ đšđŒâđ§ đ©đŒâđŹ đ§đŒâđŹ đšđŒâđŹ đ©đŒâđš đ§đŒâđš đšđŒâđš đ©đŒâđ đ§đŒâđ đšđŒâđ đ©đŒââïž đ§đŒââïž đšđŒââïž đ©đŒâđ đ§đŒâđ đšđŒâđ đ©đŒââïž đ§đŒââïž đšđŒââïž đ°đŒââïž đ°đŒ đ°đŒââïž đ€”đŒââïž đ€”đŒ đ€”đŒââïž đžđŒ đ€ŽđŒ đ„·đŒ đŠžđŒââïž đŠžđŒ đŠžđŒââïž đŠčđŒââïž đŠčđŒ đŠčđŒââïž đ€¶đŒ đ§đŒâđ đ đŒ đ§đŒââïž đ§đŒ đ§đŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đŒđŒ đ€°đŒ đ€±đŒ đ©đŒâđŒ đ§đŒâđŒ đšđŒâđŒ đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đ đŒââïž đ đŒ đ đŒââïž đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đ€ŠđŒââïž đ€ŠđŒ đ€ŠđŒââïž đ€·đŒââïž đ€·đŒ đ€·đŒââïž đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đđŒ đșđŒ đŽđŒ đ©đŒâđŠœ đ§đŒâđŠœ đšđŒâđŠœ đ©đŒâđŠŒ đ§đŒâđŠŒ đšđŒâđŠŒ đ¶đŒââïž đ¶đŒ đ¶đŒââïž đ©đŒâ𩯠đ§đŒâ𩯠đšđŒâ𩯠đ§đŒââïž đ§đŒ đ§đŒââïž đđŒââïž đđŒ đđŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đđŒ đ§đŒâđ€âđ§đŒ đŹđŒ đ«đŒ đ§đŒââïž đ§đŒ đ§đŒââïž đđŒ đđŒ đđŒââïž đđŒ đđŒââïž đđŒââïž đđŒ đđŒââïž đŁđŒââïž đŁđŒ đŁđŒââïž đđŒââïž đđŒ đđŒââïž âčđŒââïž âčđŒ âčđŒââïž đđŒââïž đđŒ đđŒââïž đŽđŒââïž đŽđŒ đŽđŒââïž đ”đŒââïž đ”đŒ đ”đŒââïž đ€žđŒââïž đ€žđŒ đ€žđŒââïž đ€œđŒââïž đ€œđŒ đ€œđŒââïž đ€ŸđŒââïž đ€ŸđŒ đ€ŸđŒââïž đ€čđŒââïž đ€čđŒ đ€čđŒââïž đ§đŒââïž đ§đŒ đ§đŒââïž đđŒ đđŒ
Brown Emojis
đđœ đ€đœ đđœ âđœ đđœ đđœ đ€đœ đ€đœ âđœ đ€đœ đ€đœ đ€đœ đ€đœ đđœ đđœ đđœ đđœ đđœ âđœ đđœ đđœ âđœ đđœ đ€đœ đ€đœ đđœ đđœ đđœ đ€Čđœ đđœ âđœ đ đœ đ€łđœ đȘđœ đŠ”đœ đжđœ đđœ đŠ»đœ đđœ đ¶đœ đ§đœ đ§đœ đŠđœ đ©đœ đ§đœ đšđœ đ©đœâđŠ± đ§đœâđŠ± đšđœâđŠ± đ©đœâ𩰠đ§đœâ𩰠đšđœâ𩰠đ±đœââïž đ±đœ đ±đœââïž đ©đœâ𩳠đ§đœâ𩳠đšđœâ𩳠đ©đœâđŠČ đ§đœâđŠČ đšđœâđŠČ đ§đœ đ”đœ đ§đœ đŽđœ đČđœ đłđœââïž đłđœ đłđœââïž đ§đœ đźđœââïž đźđœ đźđœââïž đ·đœââïž đ·đœ đ·đœââïž đđœââïž đđœ đđœââïž đ”đœââïž đ”đœ đ”đœââïž đ©đœââïž đ§đœââïž đšđœââïž đ©đœâđŸ đ§đœâđŸ đšđœâđŸ đ©đœâđł đ§đœâđł đšđœâđł đ©đœâđ đ§đœâđ đšđœâđ đ©đœâđ€ đ§đœâđ€ đšđœâđ€ đ©đœâđ« đ§đœâđ« đšđœâđ« đ©đœâđ đ§đœâđ đšđœâđ đ©đœâđ» đ§đœâđ» đšđœâđ» đ©đœâđŒ đ§đœâđŒ đšđœâđŒ đ©đœâđ§ đ§đœâđ§ đšđœâđ§ đ©đœâđŹ đ§đœâđŹ đšđœâđŹ đ©đœâđš đ§đœâđš đšđœâđš đ©đœâđ đ§đœâđ đšđœâđ đ©đœââïž đ§đœââïž đšđœââïž đ©đœâđ đ§đœâđ đšđœâđ đ©đœââïž đ§đœââïž đšđœââïž đ°đœââïž đ°đœ đ°đœââïž đ€”đœââïž đ€”đœ đ€”đœââïž đžđœ đ€Žđœ đ„·đœ đŠžđœââïž đŠžđœ đŠžđœââïž đŠčđœââïž đŠčđœ đŠčđœââïž đ€¶đœ đ§đœâđ đ đœ đ§đœââïž đ§đœ đ§đœââïž đ§đœââïž đ§đœ đ§đœââïž đ§đœââïž đ§đœ đ§đœââïž đ§đœââïž đ§đœ đ§đœââïž đ§đœââïž đ§đœ đ§đœââïž đŒđœ đ€°đœ đ€±đœ đ©đœâđŒ đ§đœâđŒ đšđœâđŒ đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đ đœââïž đ đœ đ đœââïž đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đ§đœââïž đ§đœ đ§đœââïž đ€Šđœââïž đ€Šđœ đ€Šđœââïž đ€·đœââïž đ€·đœ đ€·đœââïž đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đ§đœââïž đ§đœ đ§đœââïž đđœ đșđœ đŽđœ đ©đœâđŠœ đ§đœâđŠœ đšđœâđŠœ đ©đœâđŠŒ đ§đœâđŠŒ đšđœâđŠŒ đ¶đœââïž đ¶đœ đ¶đœââïž đ©đœâ𩯠đ§đœâ𩯠đšđœâ𩯠đ§đœââïž đ§đœ đ§đœââïž đđœââïž đđœ đđœââïž đ§đœââïž đ§đœ đ§đœââïž đđœ đ§đœâđ€âđ§đœ đŹđœ đ«đœ đ§đœââïž đ§đœ đ§đœââïž đđœ đđœ đđœââïž đđœ đđœââïž đđœââïž đđœ đđœââïž đŁđœââïž đŁđœ đŁđœââïž đđœââïž đđœ đđœââïž âčđœââïž âčđœ âčđœââïž đđœââïž đđœ đđœââïž đŽđœââïž đŽđœ đŽđœââïž đ”đœââïž đ”đœ đ”đœââïž đ€žđœââïž đ€žđœ đ€žđœââïž đ€œđœââïž đ€œđœ đ€œđœââïž đ€Ÿđœââïž đ€Ÿđœ đ€Ÿđœââïž đ€čđœââïž đ€čđœ đ€čđœââïž đ§đœââïž đ§đœ đ§đœââïž đđœ đđœ
Dark Brown Emojis
đđŸ đ€đŸ đđŸ âđŸ đđŸ đđŸ đ€đŸ đ€đŸ âđŸ đ€đŸ đ€đŸ đ€đŸ đ€đŸ đđŸ đđŸ đđŸ đđŸ đđŸ âđŸ đđŸ đđŸ âđŸ đđŸ đ€đŸ đ€đŸ đđŸ đđŸ đđŸ đ€ČđŸ đđŸ âđŸ đ đŸ đ€łđŸ đȘđŸ đŠ”đŸ đжđŸ đđŸ đŠ»đŸ đđŸ đ¶đŸ đ§đŸ đ§đŸ đŠđŸ đ©đŸ đ§đŸ đšđŸ đ©đŸâđŠ± đ§đŸâđŠ± đšđŸâđŠ± đ©đŸâ𩰠đ§đŸâ𩰠đšđŸâ𩰠đ±đŸââïž đ±đŸ đ±đŸââïž đ©đŸâ𩳠đ§đŸâ𩳠đšđŸâ𩳠đ©đŸâđŠČ đ§đŸâđŠČ đšđŸâđŠČ đ§đŸ đ”đŸ đ§đŸ đŽđŸ đČđŸ đłđŸââïž đłđŸ đłđŸââïž đ§đŸ đźđŸââïž đźđŸ đźđŸââïž đ·đŸââïž đ·đŸ đ·đŸââïž đđŸââïž đđŸ đđŸââïž đ”đŸââïž đ”đŸ đ”đŸââïž đ©đŸââïž đ§đŸââïž đšđŸââïž đ©đŸâđŸ đ§đŸâđŸ đšđŸâđŸ đ©đŸâđł đ§đŸâđł đšđŸâđł đ©đŸâđ đ§đŸâđ đšđŸâđ đ©đŸâđ€ đ§đŸâđ€ đšđŸâđ€ đ©đŸâđ« đ§đŸâđ« đšđŸâđ« đ©đŸâđ đ§đŸâđ đšđŸâđ đ©đŸâđ» đ§đŸâđ» đšđŸâđ» đ©đŸâđŒ đ§đŸâđŒ đšđŸâđŒ đ©đŸâđ§ đ§đŸâđ§ đšđŸâđ§ đ©đŸâđŹ đ§đŸâđŹ đšđŸâđŹ đ©đŸâđš đ§đŸâđš đšđŸâđš đ©đŸâđ đ§đŸâđ đšđŸâđ đ©đŸââïž đ§đŸââïž đšđŸââïž đ©đŸâđ đ§đŸâđ đšđŸâđ đ©đŸââïž đ§đŸââïž đšđŸââïž đ°đŸââïž đ°đŸ đ°đŸââïž đ€”đŸââïž đ€”đŸ đ€”đŸââïž đžđŸ đ€ŽđŸ đ„·đŸ đŠžđŸââïž đŠžđŸ đŠžđŸââïž đŠčđŸââïž đŠčđŸ đŠčđŸââïž đ€¶đŸ đ§đŸâđ đ đŸ đ§đŸââïž đ§đŸ đ§đŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đŒđŸ đ€°đŸ đ€±đŸ đ©đŸâđŒ đ§đŸâđŒ đšđŸâđŒ đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đ đŸââïž đ đŸ đ đŸââïž đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đ€ŠđŸââïž đ€ŠđŸ đ€ŠđŸââïž đ€·đŸââïž đ€·đŸ đ€·đŸââïž đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đđŸ đșđŸ đŽđż đ©đŸâđŠœ đ§đŸâđŠœ đšđŸâđŠœ đ©đŸâđŠŒ đ§đŸâđŠŒ đšđŸâđŠŒ đ¶đŸââïž đ¶đŸ đ¶đŸââïž đ©đŸâ𩯠đ§đŸâ𩯠đšđŸâ𩯠đ§đŸââïž đ§đŸ đ§đŸââïž đđŸââïž đđŸ đđŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đđŸ đ§đŸâđ€âđ§đŸ đŹđŸ đ«đŸ đ§đŸââïž đ§đŸ đ§đŸââïž đđŸ đđŸ đđŸââïž đđŸ đđŸââïž đđŸââïž đđŸ đđŸââïž đŁđŸââïž đŁđŸ đŁđŸââïž đđŸââïž đđŸ đđŸââïž âčđŸââïž âčđŸ âčđŸââïž đđŸââïž đđŸ đđŸââïž đŽđŸââïž đŽđŸ đŽđŸââïž đ”đŸââïž đ”đŸ đ”đŸââïž đ€žđŸââïž đ€žđŸ đ€žđŸââïž đ€œđŸââïž đ€œđŸ đ€œđŸââïž đ€ŸđŸââïž đ€ŸđŸ đ€ŸđŸââïž đ€čđŸââïž đ€čđŸ đ€čđŸââïž đ§đŸââïž đ§đŸ đ§đŸââïž đđŸ đđŸ
Black Emojis
đđż đ€đż đđż âđż đđż đđż đ€đż đ€đż âđż đ€đż đ€đż đ€đż đ€đż đđż đđż đđż đđż đđż âđż đđż đđż âđż đđż đ€đż đ€đż đđż đđż đđż đ€Čđż đđż âđż đ đż đ€łđż đȘđż đŠ”đż đжđż đđż đŠ»đż đđż đ¶đż đ§đż đ§đż đŠđż đ©đż đ§đż đšđż đ©đżâđŠ± đ§đżâđŠ± đšđżâđŠ± đ©đżâ𩰠đ§đżâ𩰠đšđżâ𩰠đ±đżââïž đ±đż đ±đżââïž đ©đżâ𩳠đ§đżâ𩳠đšđżâ𩳠đ©đżâđŠČ đ§đżâđŠČ đšđżâđŠČ đ§đż đ”đż đ§đż đŽđż đČđż đłđżââïž đłđż đłđżââïž đ§đż đźđżââïž đźđż đźđżââïž đ·đżââïž đ·đż đ·đżââïž đđżââïž đđż đđżââïž đ”đżââïž đ”đż đ”đżââïž đ©đżââïž đ§đżââïž đšđżââïž đ©đżâđŸ đ§đżâđŸ đšđżâđŸ đ©đżâđł đ§đżâđł đšđżâđł đ©đżâđ đ§đżâđ đšđżâđ đ©đżâđ€ đ§đżâđ€ đšđżâđ€ đ©đżâđ« đ§đżâđ« đšđżâđ« đ©đżâđ đ§đżâđ đšđżâđ đ©đżâđ» đ§đżâđ» đšđżâđ» đ©đżâđŒ đ§đżâđŒ đšđżâđŒ đ©đżâđ§ đ§đżâđ§ đšđżâđ§ đ©đżâđŹ đ§đżâđŹ đšđżâđŹ đ©đżâđš đ§đżâđš đšđżâđš đ©đżâđ đ§đżâđ đšđżâđ đ©đżââïž đ§đżââïž đšđżââïž đ©đżâđ đ§đżâđ đšđżâđ đ©đżââïž đ§đżââïž đšđżââïž đ°đżââïž đ°đż đ°đżââïž đ€”đżââïž đ€”đż đ€”đżââïž đžđż đ€Žđż đ„·đż đŠžđżââïž đŠžđż đŠžđżââïž đŠčđżââïž đŠčđż đŠčđżââïž đ€¶đż đ§đżâđ đ đż đ§đżââïž đ§đż đ§đżââïž đ§đżââïž đ§đż đ§đżââïž đ§đżââïž đ§đż đ§đżââïž đ§đżââïž đ§đż đ§đżââïž đ§đżââïž đ§đż đ§đżââïž đŒđż đ€°đż đ€±đż đ©đżâđŒ đ§đżâđŒ đšđżâđŒ đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đ đżââïž đ đż đ đżââïž đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đ§đżââïž đ§đż đ§đżââïž đ€Šđżââïž đ€Šđż đ€Šđżââïž đ€·đżââïž đ€·đż đ€·đżââïž đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đ§đżââïž đ§đż đ§đżââïž đđż đșđż đŽđż đ©đżâđŠœ đ§đżâđŠœ đšđżâđŠœ đ©đżâđŠŒ đ§đżâđŠŒ đšđżâđŠŒ đ¶đżââïž đ¶đż đ¶đżââïž đ©đżâ𩯠đ§đżâ𩯠đšđżâ𩯠đ§đżââïž đ§đż đ§đżââïž đđżââïž đđż đđżââïž đ§đżââïž đ§đż đ§đżââïž đđż đ§đżâđ€âđ§đż đŹđż đ«đż đ§đżââïž đ§đż đ§đżââïž đđż đđż đđżââïž đđż đđżââïž đđżââïž đđż đđżââïž đŁđżââïž đŁđż đŁđżââïž đđżââïž đđż đđżââïž âčđżââïž âčđż âčđżââïž đđżââïž đđż đđżââïž đŽđżââïž đŽđż đŽđżââïž đ”đżââïž đ”đż đ”đżââïž đ€žđżââïž đ€žđż đ€žđżââïž đ€œđżââïž đ€œđż đ€œđżââïž đ€Ÿđżââïž đ€Ÿđż đ€Ÿđżââïž đ€čđżââïž đ€čđż đ€čđżââïž đ§đżââïž đ§đż đ§đżââïž đđż đđż
[Animals & Nature](https://emojipedia.org/nature/ 'Names and meanings of animal and nature emojis
')
đ¶ đ± đ đč đ° đŠ đ» đŒ đ»ââïž đš đŻ đŠ đź đ· đœ đž đ” đ đ đ đ đ đ§ đŠ đ€ đŁ đ„ đŠ đŠ đŠ đŠ đș đ đŽ đŠ đ đȘ± đ đŠ đ đ đ đȘ° đȘČ đȘł đŠ đŠ đ· đž đŠ đą đ đŠ đŠ đŠ đ đŠ đŠ đŠ đŠ đĄ đ đ đŹ đł đ đŠ đ đ đ đŠ đŠ đŠ§ đŠŁ đ đŠ đŠ đȘ đ« đŠ đŠ đŠŹ đ đ đ đ đ đ đ đŠ đ đŠ đ đ© 𩼠đâđŠș đ đâ⏠đȘ¶ đ đŠ đŠ€ đŠ đŠ đŠą đŠ© đ đ đŠ đŠš đŠĄ đŠ« đŠŠ đŠ„ đ đ đż đŠ đŸ đ đČ đ” đ đČ đł đŽ đȘ” đ± đż âïž đ đ đȘŽ đ đ đ đ đ đ đȘš đŸ đ đ· đč đ„ đș đž đŒ đ» đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đȘ đ« âïž đ âš âĄïž âïž đ„ đ„ đȘ đ âïž đ€ â ïž đ„ âïž đŠ đ§ â đ© đš âïž âïž âïž đŹ đš đ§ đŠ âïž âïž đ đ«
[Food & Drink](https://emojipedia.org/food-drink/ 'Names and meanings of food and drink emojis
')
đ đ đ đ đ đ đ đ đ đ« đ đ đ đ„ đ đ„„ đ„ đ đ đ„ đ„Š đ„Ź đ„ đ¶ đ« đœ đ„ đ« đ§ đ§ đ„ đ đ„ đ„Ż đ đ„ đ„š đ§ đ„ đł đ§ đ„ đ§ đ„ đ„© đ đ 𩮠đ đ đ đ đ« đ„Ș đ„ đ§ đź đŻ đ« đ„ đ„ đ« đ„« đ đ đČ đ đŁ đ± đ„ đŠȘ đ€ đ đ đ đ„ đ„ đ„ź đą đĄ đ§ đš đŠ đ„§ đ§ đ° đ đź đ đŹ đ« đż đ© đȘ đ° đ„ đŻ đ„ đŒ đ« âïž đ” đ§ đ„€ đ§ đ¶ đș đ» đ„ đ· đ„ đž đč đ§ đŸ đ§ đ„ đŽ đœ đ„Ł đ„Ą đ„ą đ§
[Activity and Sports](https://emojipedia.org/activity/ 'Names and meanings of sport and activity emojis
')
âœïž đ đ âŸïž đ„ đŸ đ đ đ„ đ± đȘ đ đž đ đ đ„ đ đȘ đ„ âłïž đȘ đč đŁ đ€ż đ„ đ„ đœ đč đŒ đ· âž đ„ đż â· đ đȘ đïžââïž đïž đïžââïž đ€Œââïž đ€Œ đ€Œââïž đ€žââïž đ€ž đ€žââïž âčïžââïž âčïž âčïžââïž đ€ș đ€Ÿââïž đ€Ÿ đ€Ÿââïž đïžââïž đïž đïžââïž đ đ§ââïž đ§ đ§ââïž đââïž đ đââïž đââïž đ đââïž đ€œââïž đ€œ đ€œââïž đŁââïž đŁ đŁââïž đ§ââïž đ§ đ§ââïž đ”ââïž đ” đ”ââïž đŽââïž đŽ đŽââïž đ đ„ đ„ đ„ đ đ đ” đ đ« đ đȘ đ€č đ€čââïž đ€čââïž đ đ©° đš đŹ đ€ đ§ đŒ đč đ„ đȘ đ· đș đȘ đž đȘ đ» đČ â đŻ đł đź đ° đ§©
[Travel & Places](https://emojipedia.org/travel-places/ 'Names and meanings of travel and place emojis
')
đ đ đ đ đ đ đ đ đ đ đ» đ đ đ đŠŻ đŠœ đŠŒ đŽ đČ đ” đ đș đš đ đ đ đ đĄ đ đ đ đ đ đ đ đ đ đ đ đ đ đ âïž đ« đŹ đ© đș đ° đ đž đ đ¶ â”ïž đ€ đ„ đł ⎠đą âïž đȘ âœïž đ§ đŠ đ„ đ đș đż đœ đŒ đ° đŻ đ đĄ đą đ âČïž â± đ đ đ đ â° đ đ» đ âșïž đ đ đĄ đ đ đ đ đą đŹ đŁ đ€ đ„ đŠ đš đȘ đ« đ© đ đ âȘïž đ đ đ đ â© đ€ đŁ đŸ đ đ đ đ đ đ đ đ đ đ đ đ đ đ
[Objects](https://emojipedia.org/objects/ 'Names and meanings of object emojis
')
âïž đ± đČ đ» âšïž đ„ đš đ± đČ đč đ đœ đŸ đż đ đŒ đ· đž đč đ„ đœ đ đ âïž đ đ đș đ» đ đ đ đ§ â± âČ â° đ° âïž âł đĄ đ đ đĄ đŠ đŻ đȘ đ§Ż đą đž đ” đŽ đ¶ đ· đȘ đ° đł đ âïž đȘ đ§° đȘ đ§ đš â đ â đȘ đ© âïž đȘ€ đ§± â đ§Č đ« đŁ đ§š đȘ đȘ đĄ âïž đĄ đŹ â°ïž đȘŠ â±ïž đș đź đż đ§ż đ âïž đ đŹ đł đ©č đ©ș đ đ 𩞠𧏠đŠ đ§« đ§Ș đĄ đ§č đȘ đ§ș đ§» đœ đ° đż đ đ đ§Œ đȘ„ đȘ đ§œ đȘŁ đ§Ž đ đ đ đȘ đȘ đ đ đ đ§ž đȘ đŒ đȘ đȘ đ đ đ đ đ đ đȘ đȘ đ đ đ đź đ đ§§ âïž đ© đš đ§ đ đ„ đ€ đŠ đ· đȘ§ đȘ đ« đŹ đ đź đŻ đ đ đ đ đ§Ÿ đ đ đ đ đ đ đ đ đ đ đł đ đ đ đ đ đ đ° đ đ đ đ đ đ đ đ đ đ đ§· đ đ đ đ đ đ§ź đ đ âïž đ đ âïž đ đ đ âïž đ đ đ đ đ đ
[Symbols](https://emojipedia.org/objects/ 'Names and meanings of hearts and symbol emojis
')
â€ïž đ§Ą đ đ đ đ đ€ đ€ đ€ đ âŁïž đ đ đ đ đ đ đ đ âźïž âïž âȘïž đ âžïž âĄïž đŻ đ âŻïž âŠïž đ â âïž âïž âïž âïž âïž âïž âïž âïž âïž âïž âïž âïž đ âïž đ âąïž âŁïž đŽ đł đ¶ đïž đž đș đ·ïž âŽïž đ đź đ ăïž ăïž đŽ đ” đč đČ đ °ïž đ ±ïž đ đ đ Ÿïž đ â âïž đ âïž đ đ« đŻ đą âšïž đ· đŻ đł đ± đ đ” đ âïž â â â âŒïž âïž đ đ ăœïž â ïž đž đ± âïž đ° â»ïž â đŻïž đč âïž âłïž â đ đ âïž đ đ€ đ§ đŸ âżïž đ żïž đ đł đïž đ đ đ đ đč đș đŒ â§ đ» đź đŠ đ¶ đ đŁ âčïž đ€ đĄ đ đ đ đ đ đ đ 0ïžâŁ 1ïžâŁ 2ïžâŁ 3ïžâŁ 4ïžâŁ 5ïžâŁ 6ïžâŁ 7ïžâŁ 8ïžâŁ 9ïžâŁ đ đą #ïžâŁ *ïžâŁ âïž â¶ïž ➠⯠âč âș â âź â© âȘ ⫠⏠âïž đŒ đœ âĄïž âŹ ïž âŹïž âŹïž âïž âïž âïž âïž âïž âïž âȘïž â©ïž â€Žïž â€”ïž đ đ đ đ đ đ” đ¶ â â â âïž âŸ đČ đ± âąïž Â©ïž Âźïž ă°ïž â° âż đ đ đ đ đ âïž âïž đ đŽ đ đĄ đą đ” đŁ â«ïž âȘïž đ€ đș đ» đž đč đ¶ đ· đł đČ -ïž â«ïž âŸïž âœïž âŒïž â»ïž đ„ đ§ đš đ© đŠ đȘ âŹïž âŹïž đ« đ đ đ đ đ đ đŁ đą đâđš đŹ đ đŻ â ïž âŁïž â„ïž âŠïž đ đŽ đïž đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đĄ đą đŁ đ€ đ„ đŠ đ§
[Non-Emoji Symbols](https://getsymbols.com
/)
More Unicode symbols, Hieroglpyhs and Pictographs to copy and paste.
⹠⣠†℠⊠⧠â â ⯠âĄïž â© âȘ ⫠⏠â âź â¶ â· â” âž âč â â âč âš âŸ âŸ âą â â â â â â â â â ïž âŁïž â„ïž âŠïž †⧠⥠⹠â â â â â â â â â â â â â â â â â â đ â â â â đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ đ
[Flags](https://emojipedia.org/flags/ 'Names and meanings of Flag Emojis
')
Note: Windows has limited flag emoji support.
đłïž đŽ đ đ© đłïžâđ đłïžââ§ïž đŽââ ïž đŠđ« đŠđœ đŠđ± đ©đż đŠđž đŠđ© đŠđŽ đŠđź đŠđ¶ đŠđŹ đŠđ· đŠđČ đŠđŒ đŠđș đŠđč đŠđż đ§đž đ§đ đ§đ© đ§đ§ đ§đŸ đ§đȘ đ§đż đ§đŻ đ§đČ đ§đč đ§đŽ đ§đŠ đ§đŒ đ§đ· đźđŽ đ»đŹ đ§đł đ§đŹ đ§đ« đ§đź đ°đ đšđČ đšđŠ đźđš đšđ» đ§đ¶ đ°đŸ đšđ« đčđ© đšđ± đšđł đšđœ đšđš đšđŽ đ°đČ đšđŹ đšđ© đšđ° đšđ· đšđź đđ· đšđș đšđŒ đšđŸ đšđż đ©đ° đ©đŻ đ©đČ đ©đŽ đȘđš đȘđŹ đžđ» đŹđ¶ đȘđ· đȘđȘ đȘđč đȘđș đ«đ° đ«đŽ đ«đŻ đ«đź đ«đ· đŹđ« đ”đ« đčđ« đŹđŠ đŹđČ đŹđȘ đ©đȘ đŹđ đŹđź đŹđ· đŹđ± đŹđ© đŹđ” đŹđș đŹđč đŹđŹ đŹđł đŹđŒ đŹđŸ đđč đđł đđ° đđș đźđž đźđł đźđ© đźđ· đźđ¶ đźđȘ đźđČ đźđ± đźđč đŻđČ đŻđ” đ đŻđȘ đŻđŽ đ°đż đ°đȘ đ°đź đœđ° đ°đŒ đ°đŹ đ±đŠ đ±đ» đ±đ§ đ±đž đ±đ· đ±đŸ đ±đź đ±đč đ±đș đČđŽ đČđ° đČđŹ đČđŒ đČđŸ đČđ» đČđ± đČđč đČđ đČđ¶ đČđ· đČđș đŸđč đČđœ đ«đČ đČđ© đČđš đČđł đČđȘ đČđž đČđŠ đČđż đČđČ đłđŠ đłđ· đłđ” đłđ± đłđš đłđż đłđź đłđȘ đłđŹ đłđș đłđ« đ°đ” đČđ” đłđŽ đŽđČ đ”đ° đ”đŒ đ”đž đ”đŠ đ”đŹ đ”đŸ đ”đȘ đ”đ đ”đł đ”đ± đ”đč đ”đ· đ¶đŠ đ·đȘ đ·đŽ đ·đș đ·đŒ đŒđž đžđČ đžđŠ đžđł đ·đž đžđš đžđ± đžđŹ đžđœ đžđ° đžđź đŹđž đžđ§ đžđŽ đżđŠ đ°đ· đžđž đȘđž đ±đ° đ§đ± đžđ đ°đł đ±đš đ”đČ đ»đš đžđ© đžđ· đžđż đžđȘ đšđ đžđŸ đčđŒ đčđŻ đčđż đčđ đčđ± đčđŹ đčđ° đčđŽ đčđč đčđł đčđ· đčđČ đčđš đčđ» đ»đź đșđŹ đșđŠ đŠđȘ đŹđ§ đŽó §ó ąó „ó źó §ó ż đŽó §ó ąó łó Łó Žó ż đŽó §ó ąó ·ó Źó łó ż đșđł đșđž đșđŸ đșđż đ»đș đ»đŠ đ»đȘ đ»đł đŒđ« đȘđ đŸđȘ đżđČ đżđŒ
đđ People - đ»đ» Animals - đđč Food - đ·âœïž Activities - đđ Travel - đĄđ Objects - đđŁ Symbols - đđłïžâđ Flags
[New Emojis](https://emojipedia.org/new/ 'New 2019 Emojis
')
Emojis from Emoji 13.0: Added in 2020.
đ„Č đ„ž đ€ đ€đ» đ€đŒ đ€đœ đ€đŸ đ€đż đ« đ« đ„· đ€”ââïž đ€”đ»ââïž đ€”đŒââïž đ€”đœââïž đ€”đŸââïž đ€”đżââïž đ€”ââïž đ€”đ»ââïž đ€”đŒââïž đ€”đœââïž đ€”đŸââïž đ€”đżââïž đ°ââïž đ°đ»ââïž đ°đŒââïž đ°đœââïž đ°đŸââïž đ°đżââïž đ°ââïž đ°đ»ââïž đ°đŒââïž đ°đœââïž đ°đŸââïž đ°đżââïž đ©âđŒ đ©đ»âđŒ đ©đŒâđŒ đ©đœâđŒ đ©đŸâđŒ đ©đżâđŒ đ§âđŒ đ§đ»âđŒ đ§đŒâđŒ đ§đœâđŒ đ§đŸâđŒ đ§đżâđŒ đšâđŒ đšđ»âđŒ đšđŒâđŒ đšđœâđŒ đšđŸâđŒ đšđżâđŒ đ§âđ đ§đ»âđ đ§đŒâđ đ§đœâđ đ§đŸâđ đ§đżâđ đ« đââŹ đŠŹ đŠŁ đŠ« đ»ââïž đŠ€ đȘ¶ đŠ đȘČ đȘł đȘ° đȘ± đȘŽ đ« đ« đ« đ« đ« đ« đ« đ§ đȘš đȘ” đ đ» đŒ đȘ đȘ đȘ đȘĄ đȘą 𩎠đȘ đȘ đȘ đȘ đȘ đȘ đȘ đȘ đȘ đ đȘ đȘ đȘ đȘ€ đȘŁ đȘ„ đȘŠ đȘ§ đłïžââ§ïž
Emojis from Emoji 13.1: Added in 2021.
đźâđš đ”âđ« đ¶âđ«ïž â€ïžâđ„ â€ïžâđ©č đ§ââïž đ§đ»ââïž đ§đŒââïž đ§đœââïž đ§đŸââïž đ§đżââïž đ§ââïž đ§đ»ââïž đ§đŒââïž đ§đœââïž đ§đŸââïž đ§đżââïž đđ» đđŒ đđœ đđŸ đđż đđ» đđŒ đđœ đđŸ đđż đšđ»ââ€ïžâđšđ» đšđ»ââ€ïžâđšđŒ đšđ»ââ€ïžâđšđœ đšđ»ââ€ïžâđšđŸ đšđ»ââ€ïžâđšđż đšđŒââ€ïžâđšđ» đšđŒââ€ïžâđšđŒ đšđŒââ€ïžâđšđœ đšđŒââ€ïžâđšđŸ đšđŒââ€ïžâđšđż đšđœââ€ïžâđšđ» đšđœââ€ïžâđšđŒ đšđœââ€ïžâđšđœ đšđœââ€ïžâđšđŸ đšđœââ€ïžâđšđż đšđŸââ€ïžâđšđ» đšđŸââ€ïžâđšđŒ đšđŸââ€ïžâđšđœ đšđŸââ€ïžâđšđŸ đšđŸââ€ïžâđšđż đšđżââ€ïžâđšđ» đšđżââ€ïžâđšđŒ đšđżââ€ïžâđšđœ đšđżââ€ïžâđšđŸ đšđżââ€ïžâđšđż đ©đ»ââ€ïžâđšđ» đ©đ»ââ€ïžâđšđŒ đ©đ»ââ€ïžâđšđœ đ©đ»ââ€ïžâđšđŸ đ©đ»ââ€ïžâđšđż đ©đ»ââ€ïžâđ©đ» đ©đ»ââ€ïžâđ©đŒ đ©đ»ââ€ïžâđ©đœ đ©đ»ââ€ïžâđ©đŸ đ©đ»ââ€ïžâđ©đż đ©đŒââ€ïžâđšđ» đ©đŒââ€ïžâđšđŒ đ©đŒââ€ïžâđšđœ đ©đŒââ€ïžâđšđŸ đ©đŒââ€ïžâđšđż đ©đŒââ€ïžâđ©đ» đ©đŒââ€ïžâđ©đŒ đ©đŒââ€ïžâđ©đœ đ©đŒââ€ïžâđ©đŸ đ©đŒââ€ïžâđ©đż đ©đœââ€ïžâđšđ» đ©đœââ€ïžâđšđŒ đ©đœââ€ïžâđšđœ đ©đœââ€ïžâđšđŸ đ©đœââ€ïžâđšđż đ©đœââ€ïžâđ©đ» đ©đœââ€ïžâđ©đŒ đ©đœââ€ïžâđ©đœ đ©đœââ€ïžâđ©đŸ đ©đœââ€ïžâđ©đż đ©đŸââ€ïžâđšđ» đ©đŸââ€ïžâđšđŒ đ©đŸââ€ïžâđšđœ đ©đŸââ€ïžâđšđŸ đ©đŸââ€ïžâđšđż đ©đŸââ€ïžâđ©đ» đ©đŸââ€ïžâđ©đŒ đ©đŸââ€ïžâđ©đœ đ©đŸââ€ïžâđ©đŸ đ©đŸââ€ïžâđ©đż đ©đżââ€ïžâđšđ» đ©đżââ€ïžâđšđŒ đ©đżââ€ïžâđšđœ đ©đżââ€ïžâđšđŸ đ©đżââ€ïžâđšđż đ©đżââ€ïžâđ©đ» đ©đżââ€ïžâđ©đŒ đ©đżââ€ïžâđ©đœ đ©đżââ€ïžâđ©đŸ đ©đżââ€ïžâđ©đż đ§đ»ââ€ïžâđ§đŒ đ§đ»ââ€ïžâđ§đœ đ§đ»ââ€ïžâđ§đŸ đ§đ»ââ€ïžâđ§đż đ§đŒââ€ïžâđ§đ» đ§đŒââ€ïžâđ§đœ đ§đŒââ€ïžâđ§đŸ đ§đŒââ€ïžâđ§đż đ§đœââ€ïžâđ§đ» đ§đœââ€ïžâđ§đŒ đ§đœââ€ïžâđ§đŸ đ§đœââ€ïžâđ§đż đ§đŸââ€ïžâđ§đ» đ§đŸââ€ïžâđ§đŒ đ§đŸââ€ïžâđ§đœ đ§đŸââ€ïžâđ§đż đ§đżââ€ïžâđ§đ» đ§đżââ€ïžâđ§đŒ đ§đżââ€ïžâđ§đœ đ§đżââ€ïžâđ§đŸ đšđ»ââ€ïžâđâđšđ» đšđ»ââ€ïžâđâđšđŒ đšđ»ââ€ïžâđâđšđœ đšđ»ââ€ïžâđâđšđŸ đšđ»ââ€ïžâđâđšđż đšđŒââ€ïžâđâđšđ» đšđŒââ€ïžâđâđšđŒ đšđŒââ€ïžâđâđšđœ đšđŒââ€ïžâđâđšđŸ đšđŒââ€ïžâđâđšđż đšđœââ€ïžâđâđšđ» đšđœââ€ïžâđâđšđŒ đšđœââ€ïžâđâđšđœ đšđœââ€ïžâđâđšđŸ đšđœââ€ïžâđâđšđż đšđŸââ€ïžâđâđšđ» đšđŸââ€ïžâđâđšđŒ đšđŸââ€ïžâđâđšđœ đšđŸââ€ïžâđâđšđŸ đšđŸââ€ïžâđâđšđż đšđżââ€ïžâđâđšđ» đšđżââ€ïžâđâđšđŒ đšđżââ€ïžâđâđšđœ đšđżââ€ïžâđâđšđŸ đšđżââ€ïžâđâđšđż đ©đ»ââ€ïžâđâđšđ» đ©đ»ââ€ïžâđâđšđŒ đ©đ»ââ€ïžâđâđšđœ đ©đ»ââ€ïžâđâđšđŸ đ©đ»ââ€ïžâđâđšđż đ©đ»ââ€ïžâđâđ©đ» đ©đ»ââ€ïžâđâđ©đŒ đ©đ»ââ€ïžâđâđ©đœ đ©đ»ââ€ïžâđâđ©đŸ đ©đ»ââ€ïžâđâđ©đż đ©đŒââ€ïžâđâđšđ» đ©đŒââ€ïžâđâđšđŒ đ©đŒââ€ïžâđâđšđœ đ©đŒââ€ïžâđâđšđŸ đ©đŒââ€ïžâđâđšđż đ©đŒââ€ïžâđâđ©đ» đ©đŒââ€ïžâđâđ©đŒ đ©đŒââ€ïžâđâđ©đœ đ©đŒââ€ïžâđâđ©đŸ đ©đŒââ€ïžâđâđ©đż đ©đœââ€ïžâđâđšđ» đ©đœââ€ïžâđâđšđŒ đ©đœââ€ïžâđâđšđœ đ©đœââ€ïžâđâđšđŸ đ©đœââ€ïžâđâđšđż đ©đœââ€ïžâđâđ©đ» đ©đœââ€ïžâđâđ©đŒ đ©đœââ€ïžâđâđ©đœ đ©đœââ€ïžâđâđ©đŸ đ©đœââ€ïžâđâđ©đż đ©đŸââ€ïžâđâđšđ» đ©đŸââ€ïžâđâđšđŒ đ©đŸââ€ïžâđâđšđœ đ©đŸââ€ïžâđâđšđŸ đ©đŸââ€ïžâđâđšđż đ©đŸââ€ïžâđâđ©đ» đ©đŸââ€ïžâđâđ©đŒ đ©đŸââ€ïžâđâđ©đœ đ©đŸââ€ïžâđâđ©đŸ đ©đŸââ€ïžâđâđ©đż đ©đżââ€ïžâđâđšđ» đ©đżââ€ïžâđâđšđŒ đ©đżââ€ïžâđâđšđœ đ©đżââ€ïžâđâđšđŸ đ©đżââ€ïžâđâđšđż đ©đżââ€ïžâđâđ©đ» đ©đżââ€ïžâđâđ©đŒ đ©đżââ€ïžâđâđ©đœ đ©đżââ€ïžâđâđ©đŸ đ©đżââ€ïžâđâđ©đż đ§đ»ââ€ïžâđâđ§đŒ đ§đ»ââ€ïžâđâđ§đœ đ§đ»ââ€ïžâđâđ§đŸ đ§đ»ââ€ïžâđâđ§đż đ§đŒââ€ïžâđâđ§đ» đ§đŒââ€ïžâđâđ§đœ đ§đŒââ€ïžâđâđ§đŸ đ§đŒââ€ïžâđâđ§đż đ§đœââ€ïžâđâđ§đ» đ§đœââ€ïžâđâđ§đŒ đ§đœââ€ïžâđâđ§đŸ đ§đœââ€ïžâđâđ§đż đ§đŸââ€ïžâđâđ§đ» đ§đŸââ€ïžâđâđ§đŒ đ§đŸââ€ïžâđâđ§đœ đ§đŸââ€ïžâđâđ§đż đ§đżââ€ïžâđâđ§đ» đ§đżââ€ïžâđâđ§đŒ đ§đżââ€ïžâđâđ§đœ đ§đżââ€ïžâđâđ§đŸ
title: Promise.all() weight: 0 excerpt: seo: title: 'Promise.all()' description: '' robots: [] extra: [] type: stackbit_page_meta
template: docs
Promise.all()
The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.
1\. Why are frameworks useful
?
Essentially the allure of these is the amount of time that is saved and the resulting efficiency in getting a project rolled out faster because there's a lot less of the initial work to be done.
Frameworks take care of tasks like default browser settings, file structures, and layout templates for your website. This automation generates a uniform design for page elements like text, tables, forms, and buttons, amongst other things. Even complex navigation menus become standardized with frameworks as it can be consistently applied across your website with ease.
2\. Types of framework
There are many different kinds of this platform available for programmers. Typically, like a lot of things within this discipline can be split between frontend and backend development---first let's make the distinction between the two to help you understand the usefulness of these solutions.
Backend frameworks
These are designed to make the responsibility of interacting with the database an easier endeavor for the developer. It automates a lot of functions and processes that web developers use to record and retrieve user-inputted data.
Frontend frameworks
As the name suggests, these are very helpful on the presentation side of the website, creating a good foundation from which to build pages. These frameworks combine HTML, CSS, and Javascript to be really effective in creating conventions for various elements. Typically frontend web developers use them in conjunction with other effective tools.
HTML conventions allow for standardization for elements like typography, while CSS conventions can help standardize positioning of elements in a grid-like system on the pages. This makes it easier for the developer to arrange and organize elements into a simple and uniform design across multiple displays and browsers. Javascript conventions offer the ability to style more advanced components like image carousels, lightboxes, button behaviors, and pop-ups.
On another note, there are Javascript frameworks that focus on full application support---like AngularJS and Reactjs. Libraries of Javascript code like jQuery are also helpful in developing conventions that can be readily implemented in websites.
To recap, the use of these tools helps the developer get up and running quickly without having to get bogged down with the initial hurdles that come with setting up a website. It creates uniform code across all pages of your website and presents a clean look for users. This in turn solves common issues like typography consistency and positioning difficulties on different pages.
Best of all, frontend frameworks resolve any issues with browser compatibility and are key to responsive web design, which we'll discuss further on.
Curious about a careerin Web Development?
Start learning for free!
3\. Popular frameworks
There are many of these tools that have become must-haves for beginner and expert web developers alike. As well as different languages, they focus on different directives and outcomes.
One of the most popular frameworks is Bootstrap, which was originally developed by Twitter to maintain consistency in their interface development. It's very polished and efficient, and makes website development easier and faster. It has standardized conventions that are well recognized for HTML elements like buttons, alerts, forms, and typography.
So popular that it's now known simply as "Rails," Ruby on Rails has revolutionised this language. As well as making it one of the easier programming languages to learn, Rails is particularly popular with beginners looking to code full-stack early on in their careers.
Foundation was created from the Zurb style guide and much like Bootstrap, offers a complete solution for front-end design. Many large companies like Facebook, Yahoo, and Ebay utilize Foundation in their layouts. The framework encourages web developers to expand on the conventions and personalize them for developers' websites.
Skeleton is a lighter example that doesn't come with all the bells and whistles that accompany the heavy-lifters like Bootstrap and Foundation. This encourages greater customization by only providing styling on the most basic and necessary elements. Developers who only need specific components to be styled utilize light-weight frameworks like Skeleton to achieve their goals.
A simple Google search will turn up a lot of results for top tools being used and recommended. It's definitely beneficial to check out the different options and see which suits your development needs and design goals.
4\. How do I use frameworks
?
Regardless of whether a developer uses a full frontend framework like Bootstrap or a lightweight option like Skeleton, these are efficient tools that should be seriously considered in every developer's process.
Recognized frameworks offer more ease in collaboration as developers can access the same libraries for design conventions without having to resort to individual opinionated decisions. Additionally, there is support from the specific community with tutorials and articles on how to effectively use it.
The ease of implementation and efficiency makes it almost a necessity to employ these tools in a web developer's process. Any time a programmer is finding themselves creating an ever-growing proprietary list of CSS rules, it's probably a good idea to look into using a framework to tidy things up.
5\. What is a responsive framework
?
One of the best features of these systems is that they help create websites that are easily accessible and are able to be viewed across different browsers on different devices. A lot of frameworks accomplish this with dynamic code---utilizing classes that can be reused and formatted to take into consideration the device and/or browser that is being used.
In other words, the layouts of webpages will change---certain elements will disappear and text will be smaller on smaller screens, while certain Javascript elements might not take effect at all. On larger screens, the extra real estate can be used to showcase higher quality images and more sophisticated design elements, as well as allowing for the white space beloved by web designers.
In this current age when users are more likely to view websites on their mobile devices than their computers, it's important to have a mobile responsive website that creates an enriching user experience no matter what interface the user interacts with. In this video, our in-house web developer Abhi explains more about styling a mobile-responsive website with CSS:
6\. Final thoughts
Critics of frontend frameworks cite them as the source of a lot of cookie-cutter websites that are identical in appearance and interaction. This however, is an oversimplification. Why? Let's go back to the cooking example: a spatula is just a spatula---a lot of people have one and use the tool in the kitchen. But the food that is created will vary wildly across the spectrum, depending on the cook.
In the same light, frontend frameworks are simply a tool that can be employed to create diverse and distinctive websites. Yes they're efficient, but it's up to the developer to make sure they're effective.
If you want to learn some more about web development right now, these articles may interest you:
title: Promise.any() weight: 0 excerpt: seo: title: ' Promise.any()' description: '' robots: [] extra: [] type: stackbit_page_meta
template: docs
Promise.any()
Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors. Essentially, this method is the opposite of Promise.all().
Prefer `const` and `let` over `var
`
If you've worked with ES5 JavaScript before, you're likely used to seeing variables declared with var:
//
ar myVariable = 5;
Both the const and let statements also declare variables. They were introduced in ES6.
Use const in cases where a variable is never re-assigned. Using const makes this clear to whoever is reading your code. It refers to the "constant" state of the variable in the context it is defined within.
If the variable will be re-assigned, use let.
We encourage the use of const and let instead of var. In addition to the restriction introduced by const, both const and let are block scoped as opposed to function scoped. This scoping can help avoid unexpected bugs.
Arrow functions
ES6 introduced a new concept named arrow function. In arrow functions, JavaScript sets the this lexically.
It means the arrow function does not create its own execution context but inherits the this from the outer function where the arrow function is defined. See the following example:
//
let getThis = () => this;
console.log(getThis() === window); // trueCode language: JavaScript (javascript)
In this example, the this value is set to the global object i.e., window in the web browser.
Since an arrow function does not create its own execution context, defining a method using an arrow function will cause an issue. For example:
//
function Car() {
this.speed = 120;
}
Car.prototype.getSpeed = () => {
return this.speed;
}
var car = new Car();
car.getSpeed(); // TypeErrorCode language: JavaScript (javascript)
Inside the getSpeed() method, the this value reference the global object, not the Car object. Therefore the car.getSpeed() invocation causes an error because the global object does not have the speed property.
title: This weight: 0 excerpt: In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). seo: title: 'Javascript Quick Tips Directory' description: 'A this behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.' robots: [] extra: [] type: stackbit_page_meta
template: docs
this
A this behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).
Modules
ES6 formally supports modules using the import/export syntax.
Named exports
Inside any file, you can use export to specify a variable the module should expose. Here's an example of a file that exports two functions:
//
export const sayHi = () => console.log('Hi!');
export const sayBye = () => console.log('Bye!');
const saySomething = () => console.log('Something!');
Now, anywhere we wanted to use these functions we could use import. We need to specify which functions we want to import. A common way of doing this is using ES6's destructuring assignment syntax to list them out like this:
//
import { sayHi, sayBye } from './greetings';
sayHi();
sayBye();
Importantly, the function that was not exported (saySomething) is unavailable outside of the module.
Also note that we supply a relative path to from, indicating that the ES6 module is a local file as opposed to an npm package.
Instead of inserting an export before each variable you'd like to export, you can use this syntax to list off all the exposed variables in one area:
//
const sayHi = () => console.log('Hi!');
const sayBye = () => console.log('Bye!');
const saySomething = () => console.log('Something!');
export { sayHi, sayBye };
We can also specify that we'd like to import all of a module's functionality underneath a given namespace with the import * as <Namespace> syntax:
//
import * as Greetings from './greetings';
Greetings.sayHi();
Greetings.sayBye();
Greetings.saySomething();
Default export
The other type of export is a default export. A module can only contain one default export:
//
const sayHi = () => console.log('Hi!');
const sayBye = () => console.log('Bye!');
const saySomething = () => console.log('Something!');
const Greetings = { sayHi, sayBye };
export default Greetings;
This is a common pattern for libraries. It means you can easily import the library wholesale without specifying what individual functions you want:
//
import Greetings from './greetings';
Greetings.sayHi();
Greetings.sayBye();
It's not uncommon for a module to use a mix of both named exports and default exports. For instance, with react-dom, you can import ReactDOM (a default export) like this:
//
import ReactDOM from 'react-dom';
ReactDOM.render();
Or, if you're only going to use the render() function, you can import the named render() function like this:
//
import { render } from 'react-dom';
render();
To achieve this flexibility, the export implementation for react-dom looks something like this:
//
export const render = (component, target) => {};
const ReactDOM = {
render
};
export default ReactDOM;
If you want to play around with the module syntax, check out the folder code/webpack/es6-modules.
For more reading on ES6 modules, see this article from Mozilla: "ES6 in Depth: Modules".
`Object.assign
()`
We use Object.assign() often throughout the book. We use it in areas where we want to create a modified version of an existing object.
Object.assign() accepts any number of objects as arguments. When the function receives two arguments, it copies the properties of the second object onto the first, like so:
//
onst coffee = { };
const noCream = { cream: false };
const noMilk = { milk: false };
Object.assign(coffee, noCream);
It is idiomatic to pass in three arguments to Object.assign(). The first argument is a new JavaScript object, the one that Object.assign() will ultimately return. The second is the object whose properties we'd like to build off of. The last is the changes we'd like to apply:
//
const coffeeWithMilk = Object.assign({}, coffee, { milk: true });
Object.assign() is a handy method for working with "immutable" JavaScript objects.
Template literals
In ES5 JavaScript, you'd interpolate variables into strings like this:
//
var greeting = 'Hello, ' + user + '! It is ' + degF + ' degrees outside.';
With ES6 template literals, we can create the same string like this:
//
const greeting = `Hello, ${user}! It is ${degF} degrees outside.`;
The spread operator
(...)
In arrays, the ellipsis ... operator will expand the array that follows into the parent array. The spread operator enables us to succinctly construct new arrays as a composite of existing arrays.
Here is an example:
//
onst a = [ 1, 2, 3 ];
const b = [ 4, 5, 6 ];
const c = [ ...a, ...b, 7, 8, 9 ];
console.log(c);
Notice how this is different than if we wrote:
//
const d = [a, b, 7, 8, 9];
console.log(d);
Enhanced object literals
In ES5, all objects were required to have explicit key and value declarations:
//
const explicit = {
getState: getState,
dispatch: dispatch
};
In ES6, you can use this terser syntax whenever the property name and variable name are the same:
//
const implicit = {
getState,
dispatch
};
Lots of open source libraries use this syntax, so it's good to be familiar with it. But whether you use it in your own code is a matter of stylistic preference.
Default arguments
With ES6, you can specify a default value for an argument in the case that it is undefined when the function is called.
This:
//
unction divide(a, b) {
const divisor = typeof b === 'undefined' ? 1 : b;
return a / divisor;
}
Can be written as this:
//
function divide(a, b = 1) {
return a / b;
}
In both cases, using the function looks like this:
//
divide(14, 2);
divide(14, undefined);
divide(14);
Whenever the argument b in the example above is undefined, the default argument is used. Note that null will not use the default argument:
//
divide(14, null);
Destructuring assignments
For arrays
In ES5, extracting and assigning multiple elements from an array looked like this:
//
ar fruits = [ 'apples', 'bananas', 'oranges' ];
var fruit1 = fruits[0];
var fruit2 = fruits[1];
In ES6, we can use the destructuring syntax to accomplish the same task like this:
//
const [veg1, veg2] = ['asparagus', 'broccoli', 'onion'];
console.log(veg1);
console.log(veg2);
The variables in the array on the left are "matched" and assigned to the corresponding elements in the array on the right. Note that 'onion' is ignored and has no variable bound to it.
For objects
We can do something similar for extracting object properties into variables:
//
const smoothie = {
fats: ['avocado', 'peanut butter', 'greek yogurt'],
liquids: ['almond milk'],
greens: ['spinach'],
fruits: ['blueberry', 'banana']
};
const { liquids, fruits } = smoothie;
console.log(liquids);
console.log(fruits);
Parameter context matching
We can use these same principles to bind arguments inside a function to properties of an object supplied as an argument:
//
const containsSpinach = ({ greens }) => {
if (greens.find((g) => g === 'spinach')) {
return true;
} else {
return false;
}
};
containsSpinach(smoothie);
We do this often with functional React components:
//
const IngredientList = ({ ingredients, onClick }) => (
<ul className="IngredientList">
{ingredients.map((i) => (
<li key={i.id} onClick={() => onClick(i.id)} className="item">
{i.name}
</li>
))}
</ul>
);
Here, we use destructuring to extract the props into variables (ingredients and onClick) that we then use inside the component's function body.
Share To Linkedin:
title: Web Design weight: 0 excerpt: lorem-ipsum seo: title: '' description: '' robots: [] extra: []
template: docs
Three different aspects of web site production:
- Content -- the text, images, etc. What the user wants to read.
Style -- how the content is arranged on the page, fonts, colours, page style.
Behaviour -- how users interact with the site, data processing, dynamic page elements.
Since each requires different skills, a good (software) design would seperate them.
Each of these areas has a different associated technology in the web world: HTML, Cascading Style Sheets (CSS) and Javascript.
Note that it hasn't always been this way, HTML can do a bunch of Style things (eg. the \ tag) but now that we have good standards compliant browser we don't need to use them.
Archives
Original Blog Site
title: Rotate (Array) Problem Walkthrough weight: 0 excerpt: lorem-ipsum seo: title: 'Rotate (Array) Problem Walkthrough' description: ' The function should return a new array where the elements of the array are rotated to the right number times. The function should not mutate the original array and instead return a new array.' robots: [] extra: []
template: docs
Rotate (Array) Problem Walkthrough
Explanation for Rotate Right

Question
Write a function rotateRight(array, num) that takes in an array and a number as arguments.
The function should return a new array where the elements of the array are rotated to the right number times. The function should not mutate the original array and instead return a new array.
Define this function using
[*function expression syntax*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function).
HINT: you can use Array#slice to create a copy of an array
JavaScript gives us four methods to add or remove items from the beginning or end of arrays:
pop(): Remove an item from the end of an array
let cats = ['Bob', 'Willy', 'Mini'];
cats.pop(); // ['Bob', 'Willy']
pop() returns the removed item.
push(): Add items to the end of an array
let cats = ['Bob'];
cats.push('Willy'); // ['Bob', 'Willy']
cats.push('Puff', 'George'); // ['Bob', 'Willy', 'Puff', 'George']
push() returns the new array length.
shift(): Remove an item from the beginning of an array
let cats = ['Bob', 'Willy', 'Mini'];
cats.shift(); // ['Willy', 'Mini']
shift() returns the removed item.
unshift(): Add items to the beginning of an array
let cats = ['Bob'];
cats.unshift('Willy'); // ['Willy', 'Bob']
cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Bob']
unshift() returns the new array length.
We are being asked for two things:
- To return an array with all the elements shifted over 'num ' times.
- To
NOTmutate the original array
Step 1.\ We need to start the function and create a variable to hold a COPY of our input array.
let rotateRight = function (array, num) { let result = array.slice(0); };
view rawcopy-arr.js hosted with †by GitHub
Array.prototype.slice()\ The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end...developer.mozilla.org
- We assign array.slice(0) to a variable called result.
- Slicing our input array simply creates a sliced copy of the data.
- Remember that by excluding a second argument in our slice parameter allows us to slice from the first argument all the way to the end.
Step 2.\ We need to create a for loop to tell our function how many times we want to rotate.
let rotateRight = function (array, num) { let result = array.slice(0); for (var i = 0; i < num; i++) { // some code here } };
view rawfor-loop-rotate.js hosted with †by GitHub
- By setting our second delimiter to i < num we will ask our loops to run num times.
- Running num times is the same as executing the code block within num times.
Step 3.\ We need to put some executable code within our for loop to be run during every cycle.
//
let rotateRight = function (array, num) {
let result = array.slice(0);
for (var i = 0; i < num; i++) {
let ele = result.pop();
result.unshift(ele);
}
};
view rawrot.js hosted with †by GitHub
- Since we are rotating to the right, every change to our result array under the hood will look like this (if we ref. our first test case):
['a', 'b', 'c', 'd', 'e'];(how it looks like at the start)['e', 'a', 'b', 'c', 'd'];(after one run of the for loop)['d', 'e', 'a', 'b', 'c'];(after second/last run of the for loop)- To accomplish this we first need to '
pop' off or remove our last element. - Two things happen when we use this built-in function.
- Our copied array is mutated to lose it''s last ele.
- The removed element is stored in the variable we assigned to the function.
- Our second step is to add it to the start of our array, to do this we can use
unshift. - By inputting the variable we are using to hold our removed element into the parameter of unshift we are adding our element to the front of the array.
Step 4.
Now that our for loop has ended and our copied array looks just like how the answer looks, we need to output the answer.
let rotateRight = function (array, num) { let result = array.slice(0); for (var i = 0; i < num; i++) { let ele = result.pop(); result.unshift(ele); } return result; };
view rawrot2.js hosted with †by GitHub
- We accomplish this by creating a
returnline AFTER the for loop.
End Result
//
let rotateRight = function (array, num) {
let result = array.slice(0);
for (let i = 0; i < num; i++) {
let ele = result.pop();
result.unshift(ele);
}
return result;
};
//let arr = ["a", "b", "c", "d", "e"];
console.log(rotateRight(arr, 2));
//["d", "e", "a", "b", "c"];
console.log(arr);
["a", "b", "c", "d", "e"];
let animals = ["wombat", "koala", "opossum", "kangaroo"];
console.log(rotateRight(animals, 3));
//["koala", "opossum", "kangaroo", "wombat"];
console.log(animals);
//["wombat", "koala", "opossum", "kangaroo"];
view rawrotate.js hosted with †by GitHub
title: Array weight: 0 excerpt: seo: title: 'Javascript Arrays' description: 'class is a global object that is used in the construction of arrays; which are high-level, list-like objects.' robots: [] extra: [] type: stackbit_page_meta
template: docs
Array
Arrays are everywhere in JavaScript and with the new spread operators introduced in ECMAScript 6, you can do awesome things with them. In this post I will show you 3 useful tricks you can use when programming.
1. Iterating through an empty array
JavaScript arrays are sparse in nature in that there are a lot of holes in them. Try creating an array using the Array's constructor and you will see what I mean.
//
const arr = new Array(4);
[undefined, undefined, undefined, undefined];
You may find that iterating over a sparse array to apply a certain transformation is hard.
//
const arr = new Array(4);
> arr.map((elem, index) => index);
[undefined, undefined, undefined, undefined]
To solve this, you can use Array.apply when creating the array.
//
const arr = Array.apply(null, new Array(4));
> arr.map((elem, index) => index);
[0, 1, 2, 3]
2. Passing an empty parameter to a method
If you want to call a method and ignore one of its parameters, then JavaScript will complain if you keep it empty.
//
method('parameter1', , 'parameter3');
Uncaught SyntaxError: Unexpected token ,
A workaround that people usually resort to is to pass either null or undefined.
//
method('parameter1', null, 'parameter3'); // or
method('parameter1', undefined, 'parameter3');
I personally don't like using null since JavaScript treats it as an object and that's just weird. With the introduction of spread operators in ES6, there is a neater way of passing empty parameters to a method. As previously mentioned, arrays are sparse in nature and so passing empty values to it is totally okay. We'll use this to our advantage.
//
method(...['parameter1', , 'parameter3']); // works!
3. Unique array values
I always wonder why the Array constructor does not have a designated method to facilitate the use of unique array values. Spread operators are here for the rescue. Use spread operators with the Set constructor to generate unique array values.
//
const arr = [...new Set([1, 2, 3, 3])];
[1, 2, 3];
The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.
Constructor
String()
Creates a new String object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.
Static properties
get RegExp[@@species]
The constructor function that is used to create derived objects.
Static methods
[String.fromCharCode(num1 [, ...[, numN]])](string/fromcharcode)
Returns a string created by using the specified sequence of Unicode values.
[String.fromCodePoint(num1 [, ...[, numN)](string/fromcodepoint)
Returns a string created by using the specified sequence of code points.
String.raw()
Returns a string created from a raw template string.
Instance properties
String.prototype.length
Reflects the length of the string. Read-only.
Instance methods
String.prototype.at(index) This is an experimental API that should not be used in production code.
Returns the character (exactly one UTF-16 code unit) at the specified index. Accepts negative integers, which count back from the last string character.
String.prototype.charAt(index)
Returns the character (exactly one UTF-16 code unit) at the specified index.
String.prototype.charCodeAt(index)
Returns a number that is the UTF-16 code unit value at the given index.
String.prototype.codePointAt(pos)
Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified pos.
String.prototype.concat(str [, ...strN ])
Combines the text of two (or more) strings and returns a new string.
String.prototype.includes(searchString [, position])
Determines whether the calling string contains searchString.
String.prototype.endsWith(searchString [, length])
Determines whether a string ends with the characters of the string searchString.
String.prototype.indexOf(searchValue [, fromIndex])
Returns the index within the calling String object of the first occurrence of searchValue, or -1 if not found.
String.prototype.lastIndexOf(searchValue [, fromIndex])
Returns the index within the calling String object of the last occurrence of searchValue, or -1 if not found.
[String.prototype.localeCompare(compareString [, locales [, options]])](string/localecompare)
Returns a number indicating whether the reference string compareString comes before, after, or is equivalent to the given string in sort order.
String.prototype.match(regexp)
Used to match regular expression regexp against a string.
String.prototype.matchAll(regexp)
Returns an iterator of all regexp's matches.
String.prototype.normalize([form])
Returns the Unicode Normalization Form of the calling string value.
String.prototype.padEnd(targetLength [, padString])
Pads the current string from the end with a given string and returns a new string of the length targetLength.
String.prototype.padStart(targetLength [, padString])
Pads the current string from the start with a given string and returns a new string of the length targetLength.
String.prototype.repeat(count)
Returns a string consisting of the elements of the object repeated count times.
String.prototype.replace(searchFor, replaceWith)
Used to replace occurrences of searchFor using replaceWith. searchFor may be a string or Regular Expression, and replaceWith may be a string or function.
String.prototype.replaceAll(searchFor, replaceWith)
Used to replace all occurrences of searchFor using replaceWith. searchFor may be a string or Regular Expression, and replaceWith may be a string or function.
String.prototype.search(regexp)
Search for a match between a regular expression regexp and the calling string.
String.prototype.slice(beginIndex[, endIndex])
Extracts a section of a string and returns a new string.
[String.prototype.split([sep [, limit] ])](string/split)
Returns an array of strings populated by splitting the calling string at occurrences of the substring sep.
String.prototype.startsWith(searchString [, length])
Determines whether the calling string begins with the characters of string searchString.
String.prototype.substring(indexStart [, indexEnd])
Returns a new string containing characters of the calling string from (or between) the specified index (or indeces).
String.prototype.toLocaleLowerCase( [locale, ...locales])
The characters within a string are converted to lowercase while respecting the current locale.
For most languages, this will return the same as toLowerCase().
String.prototype.toLocaleUpperCase( [locale, ...locales])
The characters within a string are converted to uppercase while respecting the current locale.
For most languages, this will return the same as toUpperCase().
String.prototype.toLowerCase()
Returns the calling string value converted to lowercase.
String.prototype.toString()
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
String.prototype.toUpperCase()
Returns the calling string value converted to uppercase.
String.prototype.trim()
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
String.prototype.trimStart()
Trims whitespace from the beginning of the string.
String.prototype.trimEnd()
Trims whitespace from the end of the string.
String.prototype.valueOf()
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.
String.prototype.@@iterator()
Returns a new iterator object that iterates over the code points of a String value, returning each code point as a String value.
JS Fat Arrow Functions
Classical JavaScript function syntax doesn't provide for any flexibility, be that a 1 statement function or an unfortunate multi-page function. Every time you need a function you have to type out the dreaded function () {}. More concise function syntax was one of the many reasons why CoffeeScript gained so much momentum back in the day. This is especially pronounced in the case of tiny callback functions. Lets look at a Promise chain:
function getVerifiedToken(selector) {
return getUsers(selector)
.then(function (users) { return users[0]; })
.then(verifyUser)
.then(function (user, verifiedToken) { return verifiedToken; })
.catch(function (err) { log(err.stack); });
}
Above is more or less plausible piece of code written using classical JavaScript function syntax. Here is what the same code could look like rewritten using the arrow syntax:
function getVerifiedToken(selector) {
return getUsers(selector)
.then(users => users[0])
.then(verifyUser)
.then((user, verifiedToken) => verifiedToken)
.catch(err => log(err.stack));
}
A few important things to notice here:
- We've lost
functionand{}because all of our callback functions are one liners. - We've lost
()around the argument list when there's just one argument (rest arguments are an exception, eg(...args) => ...) - We've lost the
returnkeyword because when omitting{}, single line arrow functions perform an implicit return (these functions are often referred to as lambda functions in other languages).
It's important to reinforce the last point. Implicit return only happens for single statement arrow functions. When arrow function is declared with {}, even if it's a single statement, implicit return does not happen:
const getVerifiedToken = selector => {
return getUsers()
.then(users => users[0])
.then(verifyUser)
.then((user, verifiedToken) => verifiedToken)
.catch(err => log(err.stack));
}
Here's the really fun bit. Because our function has only one statement, we can still get rid of the {} and it will look almost exactly like CoffeeScript syntax:
const getVerifiedToken = selector =>
getUsers()
.then(users => users[0])
.then(verifyUser)
.then((user, verifiedToken) => verifiedToken)
.catch(err => log(err.stack));
Yep, the example above is completely valid ES2015 syntax (I was also surprised that it compiles fine). When we talk about single statement arrow functions, it doesn't mean the statement can't be spread out to multiple lines for better comprehension.
There's one caveat, however, with omitting {} from arrow functions -- how do you return an empty object, eg {}?
const emptyObject = () => {};
emptyObject(); // ?
Unfortunately there's no way to distinguish between empty block {} and an object {}. Because of that emptyObject() evaluates to undefined and {} interpreted as empty block. To return an empty object from fat arrow functions you have to surround it with brackets like so ({}):
const emptyObject = () => ({});
emptyObject(); // {}
Here's all of the above together:
function () { return 1; }
() => { return 1; }
() => 1
function (a) { return a * 2; }
(a) => { return a * 2; }
(a) => a * 2
a => a * 2
function (a, b) { return a * b; }
(a, b) => { return a * b; }
(a, b) => a * b
function () { return arguments[0]; }
(...args) => args[0]
() => {} // undefined
() => ({}) // {}
Lexical `this
`
The story of clobbering this in JavaScript is a really old one. Each function in JavaScript defines its own this context, which is as easy to get around as it is annoying. The example below tries to display a clock that updates every second using jQuery:
$('.current-time').each(function () {
setInterval(function () {
$(this).text(Date.now());
}, 1000);
});
When attempting to reference the DOM element this set by each in the setInterval callback, we unfortunately get a brand new this that belongs to the callback itself. A common way around this is to declare that or self variable:
$('.current-time').each(function () {
var self = this;
setInterval(function () {
$(self).text(Date.now());
}, 1000);
});
The fat arrow functions allow you to solve this problem because they don't introduce their own this:
$('.current-time').each(function () {
setInterval(() => $(this).text(Date.now()), 1000);
});
What about arguments
?
One of the caveats with arrow functions is that they also don't have their own arguments variable like regular functions:
function log(msg) {
const print = () => console.log(arguments[0]);
print(`LOG: ${msg}`);
}
log('hello'); // hello
To reiterate, fat arrow functions don't have their own this and arguments. Having said that, you can still get all arguments passed into the arrow functions using rest parameters (also known as spread operator):
function log(msg) {
const print = (...args) => console.log(args[0]);
print(`LOG: ${msg}`);
}
log('hello'); // LOG: hello
What about yield
?
Fat arrow functions can't be used as generators. That's it -- no exceptions, no caveats and no workarounds.
Bottom Line
Fat arrow functions are one of my favorite additions to JavaScript. It might be very tempting to just start using => instead of function everywhere. I've seen whole libraries written just using => and I don't think it's the right thing to do because of the special features that => introduces. I recommend using arrow functions only in places where you explicitly want to use the new features:
- Single statement functions that immediately return (lambdas)
- Functions that need to work with parent scope
this
title: Arrow function expressions weight: 0 excerpt: An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations. seo: title: 'Arrow function expressions' description: '' robots: [] extra: [] type: stackbit_page_meta
template: docs
Arrow function expressions
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Differences & Limitations:
- Does not have its own bindings to
thisorsuper, and should not be used asmethods. - Does not have
arguments, ornew.targetkeywords. - Not suitable for
call,applyandbindmethods, which generally rely on establishing a scope. - Can not be used as constructors.
- Can not use
yield, within its body.
Comparing traditional functions to arrow functions
Let's decompose a "traditional function" down to the simplest "arrow function" step-by-step: NOTE: Each step along the way is a valid "arrow function"
// Traditional Function
function (a){
return a + 100;
}
// Arrow Function Break Down
// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
return a + 100;
}
// 2. Remove the body brackets and word "return" -- the return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses
a => a + 100;
Note: As shown above, the { brackets } and ( parentheses ) and "return" are optional, but may be required.
For example, if you have multiple arguments or no arguments, you'll need to re-introduce parentheses around the arguments:
// Traditional Function
function (a, b){
return a + b + 100;
}
// Arrow Function
(a, b) => a + b + 100;
// Traditional Function (no arguments)
let a = 4;
let b = 2;
function (){
return a + b + 100;
}
// Arrow Function (no arguments)
let a = 4;
let b = 2;
() => a + b + 100;
Likewise, if the body requires additional lines of processing, you'll need to re-introduce brackets PLUS the "return" (arrow functions do not magically guess what or when you want to "return"):
// Traditional Function
function (a, b){
let chuck = 42;
return a + b + chuck;
}
// Arrow Function
(a, b) => {
let chuck = 42;
return a + b + chuck;
}
And finally, for named functions we treat arrow expressions like variables
// Traditional Function
function bob (a){
return a + 100;
}
// Arrow Function
let bob = a => a + 100;
Meta
Scope:
- This guide is for both beginners and experienced users. The goals are breadth (everything important), specificity (give concrete examples of the most common case), and brevity (avoid things that aren't essential or digressions you can easily look up elsewhere). Every tip is essential in some situation or significantly saves time over alternatives.
- This is written for Linux, with the exception of the "macOS only" and "Windows only" sections. Many of the other items apply or can be installed on other Unices or macOS (or even Cygwin).
- The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting.
- It includes both "standard" Unix commands as well as ones that require special package installs -- so long as they are important enough to merit inclusion.
Notes:
- To keep this to one page, content is implicitly included by reference. You're smart enough to look up more detail elsewhere once you know the idea or command to Google. Use
apt,yum,dnf,pacman,piporbrew(as appropriate) to install new programs. - Use Explainshell to get a helpful breakdown of what commands, options, pipes etc. do.
Basics
Httrack is a program that gets information from the Internet, looks for pointers to other information, gets that information, and so forth. If you ask it to, and have enough disk space, it will try to make a copy of the whole Internet on your computer. While this may be the answer to Dilbert's boss when he asks to get a printout of the Internet for some legal document, for most of us, we want to get copies of just the right part of the Internet, and have them nicely organized for our use. This is where httrack does a great job. Here's a simple example:
httrack "http://www.all.net/" -O "/tmp/www.all.net" "+*.all.net/*" -v
In this example, we ask httrack to start the Universal Resource Locator (URL) http://www.all.net/ and store the results under the directory /tmp/www.all.net (the -O stands for "output to") while not going beyond the bounds of all the files in the www.all.net domain and printing out any error messages along the way (-v means verbose). This is the most common way that I use httrack. Please note that this particular command might take you a while - and run you out of disk space.
This sort of a mirror image is not an identical copy of the original web site - in some ways it's better such as for local use - while in other ways it may be problematic - such as for legal use. This default mirroring method changes the URLs within the web site so that the references are made relative to the location the copy is stored in. This makes it very useful for navigating through the web site on your local machine with a web browser since most things will work as you would expect them to work. In this example, URLs that point outside of the www.all.net domain space will still point there, and if you encounter one, the web browser will try to get the data from that location.
For each of the issues discussed here - and many more - httrack has options to allow you to make different choices and get different results. This is one of the great things about httrack - and one of the the real major problems with using it without the knowledge of all that it can do. If you want to know all the things httrack can do, you might try typing:
httrack --help
Unfortunately, while this outputs a though list of options, it is somewhat less helpful it might be for those who don't know what the options all mean and haven't used them before. On the other hand, this is most useful for those who already know how to use the program but don't remember some obscure option that they haven't used for some time.
The rest of this manual is dedicated to detailing what you find in the help message and providing examples - lots and lots of examples... Here is what you get (page by page - use to move to the next page in the real program) if you type 'httrack --help':
`
httrack --help HTTrack version 3.03BETAo4 (compiled Jul 1 2001) usage: ./httrack ] [-] with options listed below: (* is the default value)
General options: O path for mirror/logfiles+cache (-O path_mirror[,path_cache_and_logfiles]) (--path ) %O top path if no path defined (-O path_mirror[,path_cache_and_logfiles])
Action options: w *mirror web sites (--mirror) W mirror web sites, semi-automatic (asks questions) (--mirror-wizard) g just get files (saved in the current directory) (--get-files) i continue an interrupted mirror using the cache Y mirror ALL links located in the first level pages (mirror links) (--mirrorlinks)
Proxy options: P proxy use (-P proxy:port or -P user:pass@proxy:port) (--proxy ) %f *use proxy for ftp (f0 don't use) (--httpproxy-ftp[=N])
Limits options: rN set the mirror depth to N ( r9999) (--depth[=N]) %eN set the external links depth to N ( %e0) (--ext-depth[=N]) mN maximum file length for a non-html file (--max-files[=N]) mN,N' for non html (N) and html (N') MN maximum overall size that can be uploaded/scanned (--max-size[=N]) EN maximum mirror time in seconds (60=1 minute, 3600=1 hour) (--max-time[=N]) AN maximum transfer rate in bytes/seconds (1000=1kb/s max) (--max-rate[=N]) %cN maximum number of connections/seconds (*%c10) GN pause transfer if N bytes reached, and wait until lock file is deleted (--max-pause[=N])
Flow control: cN number of multiple connections (c8) (--sockets[=N]) TN timeout, number of seconds after a non-responding link is shutdown (--timeout) RN number of retries, in case of timeout or non-fatal errors (R1) (--retries[=N]) JN traffic jam control, minimum transfert rate (bytes/seconds) tolerated for a link (--min-rate[=N]) HN host is abandonned if: 0=never, 1=timeout, 2=slow, 3=timeout or slow (--host-control[=N])
Links options: %P *extended parsing, attempt to parse all links, even in unknown tags or Javascript (%P0 don't use) (--extended-parsing[=N]) n get non-html files 'near' an html file (ex: an image located outside) (--near) t test all URLs (even forbidden ones) (--test) %L )
Build options: NN structure type (0 original structure, 1+: see below) (--structure[=N]) or user defined structure (-N "%h%p/%n%q.%t") LN long names (L1 long names / L0 8-3 conversion) (--long-names[=N]) KN keep original links (e.g. http://www.adr/link) (K0 relative link, K absolute links, K3 absolute URI links) (--keep-links[=N]) x replace external html links by error pages (--replace-external) %x do not include any password for external password protected websites (%x0 include) (--no-passwords) %q include query string for local files (useless, for information purpose only) (%q0 don't include) (--include-query-string) o generate output html file in case of error (404..) (o0 don't generate) (--generate-errors) X purge old files after update (X0 keep delete) (--purge-old[=N])
Spider options: bN accept cookies in cookies.txt (0=do not accept, 1=accept) (--cookies[=N]) u check document type if unknown (cgi,asp..) (u0 don't check, u1 check but /, u2 check always) (--check-type[=N]) j parse Java Classes (j0 don't parse) (--parse-java[=N]) sN follow robots.txt and meta robots tags (0=never,1=sometimes, 2=always) (--robots[=N]) %h force HTTP/1.0 requests (reduce update features, only for old servers or proxies) (--http-10) %B tolerant requests (accept bogus responses on some servers, but not standard!) (--tolerant) %s update hacks: various hacks to limit re-transfers when updating (identical size, bogus response..) (--updatehack) %A assume that a type (cgi,asp..) is always linked with a mime type (-%A php3=text/html) (--assume )
Browser ID: F user-agent field (-F "user-agent name") (--user-agent ) %F footer string in Html code (-%F "Mirrored [from host %s [file %s [at %s]]]" (--footer ) %l preffered language (-%l "fr, en, jp, *" (--language )
Log, index, cache C create/use a cache for updates and retries (C0 no cache,C1 cache is prioritary, C2 test update before) (--cache[=N]) k store all files in cache (not useful if files on disk) (--store-all-in-cache) %n do not re-download locally erased files (--do-not-recatch) %v display on screen filenames downloaded (in realtime) (--display) Q no log - quiet mode (--do-not-log) q no questions - quiet mode (--quiet) z log - extra infos (--extra-log) Z log - debug (--debug-log) v log on screen (--verbose) f log in files (--file-log) f2 one single log file (--single-log) I make an index (I0 don't make) (--index) %I make an searchable index for this mirror ( %I0 don't make) (--search-index)
Expert options: pN priority mode: ( p3) (--priority[=N]) 0 just scan, don't save anything (for checking links) 1 save only html files 2 save only non html files 3 save all files 7 get html files before, then treat other files S stay on the same directory D can only go down into subdirs U can only go to upper directories B can both go up&down into the directory structure a stay on the same address d stay on the same principal domain l stay on the same TLD (eg: .com) e go everywhere on the web %H debug HTTP headers in logfile (--debug-headers)
Guru options: (do NOT use)
#0 Filter test (-#0 '*.gif' 'www.bar.com/foo.gif')
#f Always flush log files
#FN Maximum number of filters
#h Version info
#K Scan stdin (debug)
#L Maximum number of links (-#L1000000)
#p Display ugly progress information
#P Catch URL
#R Old FTP routines (debug)
#T Generate transfer ops. log every minutes
#u Wait time
#Z Generate transfer rate statictics every minutes
#! Execute a shell command (-#! "echo hello")
Command-line specific options: V execute system command after each files ($0 is the filename: -V "rm \$0") (--userdef-cmd ) %U run the engine with another id when called as root (-%U smith) (--user )
Details: Option N N0 Site-structure (default) N1 HTML in web/, images/other files in web/images/ N2 HTML in web/HTML, images/other in web/images N3 HTML in web/, images/other in web/ N4 HTML in web/, images/other in web/xxx, where xxx is the file extension(all gif will be placed onto web/gif, for example) N5 Images/other in web/xxx and HTML in web/HTML N99 All files in web/, with random names (gadget !) N100 Site-structure, without www.domain.xxx/ N101 Identical to N1 exept that "web" is replaced by the site's name N102 Identical to N2 exept that "web" is replaced by the site's name N103 Identical to N3 exept that "web" is replaced by the site's name N104 Identical to N4 exept that "web" is replaced by the site's name N105 Identical to N5 exept that "web" is replaced by the site's name N199 Identical to N99 exept that "web" is replaced by the site's name N1001 Identical to N1 exept that there is no "web" directory N1002 Identical to N2 exept that there is no "web" directory N1003 Identical to N3 exept that there is no "web" directory (option set for g option) N1004 Identical to N4 exept that there is no "web" directory N1005 Identical to N5 exept that there is no "web" directory N1099 Identical to N99 exept that there is no "web" directory Details: User-defined option N %n Name of file without file type (ex: image) (--do-not-recatch) %N Name of file, including file type (ex: image.gif) %t File type (ex: gif) %p Path [without ending /] (ex: /someimages) %h Host name (ex: www.someweb.com) (--http-10) %M URL MD5 (128 bits, 32 ascii bytes) %Q query string MD5 (128 bits, 32 ascii bytes) %q small query string MD5 (16 bits, 4 ascii bytes) (--include-query-string) %s? Short name version (ex: %sN) %[param] param variable in query string
Shortcuts: --mirror
For many of you, the manual is now complete, but for the rest of us, I will now go through this listing one item at a time with examples... I will be here a while...
Syntax
httrack [-option] [+] [-]
The syntax of httrack is quite simple. You specify the URLs you wish to start the process from (), any options you might want to add ([-option], any filters specifying places you should ([+]) and should not ([-]) go, and end the command line by pressing . Httrack then goes off and does your bidding. For example:
httrack www.all.net/bob/
This will use the 'defaults' (those selections from the help page marked with '*' in the listing above) to image the web site. Specifically, the defauls are:
w mirror web sites %f use proxy for ftp (f0 don't use) cN number of multiple connections (c8) RN number of retries, in case of timeout or non-fatal errors (R1) %P extended parsing, attempt to parse all links, even in unknown tags or Javascript (%P0 don't use) NN name conversion type (0 original structure, 1+: see below) LN long names (L1 long names / L0 8-3 conversion) K keep original links (e.g. http://www.adr/link) (K0 relative link) o generate output html file in case of error (404..) (o0 don't generate) X purge old files after update (X0 keep delete) bN accept cookies in cookies.txt (0=do not accept, 1=accept) u check document type if unknown (cgi,asp..) (u0 don't check, u1 check but /, u2 check always) j parse Java Classes (j0 don't parse) sN follow robots.txt and meta robots tags (0=never,1=sometimes, 2=always) C create/use a cache for updates and retries (C0 no cache,C1 cache is prioritary, C2 test update before) f log file mode I make an index (I0 don't make) pN priority mode: ( p3) 3 save all files D can only go down into subdirs a stay on the same address --mirror make a mirror of site(s) (default)
Here's what all of that means:
w *mirror web sites
Automatically go though each URL you download and look for links to other URLs inside it, dowloading them as well.
%f *use proxy for ftp (f0 don't use)
If there are and links to ftp URLs (URLs using the file transfer protocol (FTP) rather than the hypertext transfer protocol HTTP), go through an ftp proxy server to get them.
cN number of multiple connections (*c8)
Use up to 8 simultaneous downloads so that at any gioven time, up to 8 URLs may be underway.
RN number of retries, in case of timeout or non-fatal errors (*R1)
Retry once if anything goes wrong with a download.
%P *extended parsing, attempt to parse all links, even in unknown tags or Javascript (%P0 don't use)
Try to parse all URLs - even if they are in Javascript, Java, tags of unknown types, or anywhere else the program can find things.
NN name conversion type (0 *original structure, 1+: see below)
Use the original directory and file structure of the web site in your mirror image of the site.
LN long names (L1 *long names / L0 8-3 conversion)
If filenames do not follow the old DOS conventions, store them with the same names used on the web site.
K keep original links (e.g. http://www.adr/link) (K0 *relative link)
Use relative rather than the original links so that URLs within this web site are adjusted to point to the files in the mirror.
o *generate output html file in case of error (404..) (o0 don't generate)
IF there are errors in downloading, create a file that indicates that the URL was not found. This makes browsing go a lot smoother.
X *purge old files after update (X0 keep delete)
Files not found on the web site that were previously there get deleted so that you have an accurate snapshot of the site as it is today - losing historical data.
bN accept cookies in cookies.txt (0=do not accept,* 1=accept)
Accept all cokkies sent to you and return them if requested. This is required for many sites to function. These cookies are only kept relative to the specific site, so you don't have to worry about your browser retaining them.
u check document type if unknown (cgi,asp..) (u0 don't check, * u1 check but /, u2 check always)
This causes different document types to be analyzed differently.
j *parse Java Classes (j0 don't parse)
This causes Java class files to be parsed looking for URLs.
sN follow robots.txt and meta robots tags (0=never,1=sometimes,* 2=always)
This tells the program to follow the wishes of the site owner with respect to limiting where robots like this one search.
C create/use a cache for updates and retries (C0 no cache,C1 cache is prioritary,* C2 test update before)
If you are downloading a site you have a previous copy of, supplemental parameters are transmitted to the server, for example the 'If-Modified-Since:' field will be used to see if files are newer than the last copy you have. If they are newer, they will be downloaded, otherwise, they will not.
f *log file mode
This retains a detailed log of any important events that took place.
I *make an index (I0 don't make)
This makes a top-level index.html file so that if you image a set of sites, you can have one place to start reviewing the set of sites.
pN priority mode: ( p3) 3 save all files
This will cause all downloaded files to be saved.
D *can only go down into subdirs
This prevents the program from going to higher level directories than the initial subdirectory, but allows lower-level subdirectories of the starting directory to be investigated.
a *stay on the same address
This indicates that only the web site(s) where the search started are to be collected. Other sites they point to are not to be imaged.
--mirror *make a mirror of site(s) (default)
This indicates that the program should try to make a copy of the site as well as it can.
Now that's a lot of options for the default - but of course there are a lot more options to go. For the most part, the rest of the options represent variations on these themes. For example, instead of saving all files, we might only want to save html files, or instead of 8 simultaneous sessions, we might want only 4.
If we wanted to make one of these changes, we would specify the option on the command line. For example:
httrack www.all.net/bob/ -c4 -B
This would restrict httrack to only use 4 siumultaneous sessions but allow it to go up the directory structure (for example to www.all.net/joe/) as well as down it (for example to www.all.net/bob/deeper/).
You can add a lot of options to a command line!
A Thorough Going Over
Now that you have an introduction, it's time for a more though coverage. This is where I go through each of the options and describe it in detail with examples... Actually, I won't quite do that. But I will get close.
Options tend to come in groups. Each group tends to be interrelated, so it's easier and more useful to go through them a group at a time with some baseline project in mind. In my case, the project is to collect all of the information on the Internet about some given subject. We will assume that, through a previous process, I have gotten a list of URLs of interest to me. Typically there will be hundreds of these URLs, and they will be a mixed bag of sites that are full of desired information, pages with lists of pointers to other sites, URLs of portions of a web site that are of interest (like Bob's home pages and subdirectories), and so forth. Let us say that for today we are looking for the definitive colleciton of Internet information on shoe sizes from around the world.
General Options
General options: O path for mirror/logfiles+cache (-O path_mirror[,path_cache_and_logfiles])
For this project, I will want to keep all of the information I gather in one place, so I will specify that output area of the project as /tmp/shoesizes by adding '-O /tmp/shoesizes' to every command line I use.. for example:
httrack http://www.shoesizes.com -O /tmp/shoesizes
The action options tell httrack how to operate at the larger level.
Action Options
Action options: w *mirror web sites W mirror web sites, semi-automatic (asks questions) g just get files (saved in the current directory) i continue an interrupted mirror using the cache Y mirror ALL links located in the first level pages (mirror links)
If I want httrack to ask me questions - such as what options to use, what sites to mirror, etc. I can tell it to ask these questions as follows:
httrack http://www.shoesizes.com -O /tmp/shoesizes -W
I can also do:
httrack OR httrack -W OR httrack -w
The '-W' options asks whether the or not a site has to be mirrored, while the '-w' option does not ask this question but asks the remainder of the questions required to mirror the site.
The -g option allows you to get the files exactly as they are and store them in the current directory. This is handy for a relatively small collection of information where organization isn't important. With this option, the html files will not even be parsed to look for other URLs. This option is useful for getting isolated files (e.g., httrack -g www.mydrivers.com/drivers/windrv32.exe).
If I start a collection process and it fails for ome reason or another - such as me interrupting it because I am running out of disk space - or a network outage - then I can restart the process by using the -i option:
httrack http://www.shoesizes.com -O /tmp/shoesizes -i
Finally, I can mirror all links in the first level pages of the URLs I specify. A good example of where to use whis would be in a case where I have a page that points to a lot of other sites and I want to get the initial information on those sites before mirroring them:
httrack http://www.shoesizes.com/othersites.html -O /tmp/shoesizes -Y
Proxy Options
Many users use a proxy for many of their functions. This is a key component in many firewalls, but it is also commonly used for anonymizing access and for exploiting higher speed communications at a remote server.
Proxy options: P proxy use (-P proxy:port or -P user:pass@proxy:port) %f *use proxy for ftp (f0 don't use)
If you are using a standard proxy that doesn't require a user ID and password, you would do something like this:
httrack http://www.shoesizes.com -O /tmp/shoesizes -P proxy.www.all.net:8080
In this case, we have asusmed that proxy.www.all.net is the host that does the proxy service and that it uses port 8080 for this service. In some cases you will have to ask your network or firewall administrator for these details, however, in most cases they should be the same as the options used in your web browser.
In some cases, a user ID and password are required for the proxy server. This is common in corporate environments where only authorized users may access the Internet.
httrack http://www.shoesizes.com -O /tmp/shoesizes -P fc:password@proxy.www.all.net:8080
In this case, the user ID 'fc' and the password 'password' are used on proxy.www.all.net port 8080. Again, your network or firewall administrator can be most helpful in addressing the specifics for your environment.
FTP normally operates through a proxy server, but for systems that have direct connections to the Internet, the following option should help:
httrack ftp://ftp.shoesizes.com -O /tmp/shoesizes -%f0
Limits Options
Limits options: rN set the mirror depth to N mN maximum file length for a non-html file mN,N' for non html (N) and html (N') MN maximum overall size that can be uploaded/scanned EN maximum mirror time in seconds (60=1 minute, 3600=1 hour) AN maximum transfer rate in bytes/seconds (1000=1kb/s max) GN pause transfer if N bytes reached, and wait until lock file is deleted %eN set the external links depth to N ( %e0) (--ext-depth[=N]) %cN maximum number of connections/seconds (%c10)
Setting limits provides the means by which you can avoid running out of disk space, CPU time, and so forth. This may be particularly helpful for those who accidentally try to image the whole Internet.
httrack http://www.shoesizes.com -O /tmp/shoesizes -r50
In this example, we limit the directlry depth to 50 levels deep. As a general rule, web sites don't go much deeper than 20 levels or so, and if you think about it, if there are only 2 subdirectories per directory level, a directory structure 50 deep would have about 10 trillion directories. Of course many sites have a small number of files many levels deep in a directory structure for various reasons. In some cases, a symbolic link will cause an infinite recursion of directory levels as well, so placing a limit may be advisable.
httrack http://www.shoesizes.com -O /tmp/shoesizes -m50000000
This example sets the maximum file length for non-HTML files to 50 megabytes. This is not an unusual length for things like tar files, and in some cases - for example when there are images of CD-ROMs to fetch from sites, you might want a limit more like 750 megabytes.
httrack http://www.shoesizes.com -O /tmp/shoesizes -m50000000,100000
In this example, we have set a limit for html files as well - at 100,000 bytes. HTML files are rarely larger than this, however, in some cases larger sizes may be needed.
httrack http://www.shoesizes.com -O /tmp/shoesizes -M1000000000
This option sets the maximum total size - in bytes - that can be uploaded from a site - in this case to 1 gigabyte. Depending on how much disk space you have, such an option may be worthwhile.
httrack http://www.shoesizes.com -O /tmp/shoesizes -E3600
This sets the maximum runtime for the download process. Of course depending on the speed of your connection it may take longer or shorter runtimes to get the same job done, and network traffic is also a factor. 3600 seconds corresponds to one hour.
httrack http://www.shoesizes.com -O /tmp/shoesizes A100000000
This option specifies the largest number of bytes per second that should be used for transfers. For example, you might want to go slow for some servers that are heavily loaded in the middle of the day, or to download slowly so that the servers at the other end are less likely to identify you as mirroring their site. The setting above limits my bandwidth to 100 million bytes per second - slow I know, but I wouldn't want to stress the rest of the Internet.
httrack http://www.shoesizes.com -O /tmp/shoesizes -G100000000
In this case, the G option is used to 'pause' a download after the first gigabyte is downloaded pending manual removal of the lockfile. This is handy of you want to download some portion of the data, move it to secondary storage, and then continue - or if you want to only download overnight and want to stop before daylight and continue the next evening. You could even combine this option with a cron job to remove the lock file so that the job automatically restarts at 7PM every night and gets another gigabyte.
httrack http://www.shoesizes.com -O /tmp/shoesizes %e5
In this case, httrack will only go to depth 5 for external links, thus not imaging the entire web, but only yhose links within 5 links of these web pages.
Also note that the interaction of these options may cause unintended consequences. For example, limiting bandwidth and download time conspire to limit the total amount of data that can be downloaded.
Flow Control Options
Flow control: cN number of multiple connections (c8) %cN maximum number of connections/seconds (%c10) TN timeout, number of seconds after a non-responding link is shutdown RN number of retries, in case of timeout or non-fatal errors (*R1) JN traffic jam control, minimum transfert rate (bytes/seconds) tolerated for a link HN host is abandonned if: 0=never, 1=timeout, 2=slow, 3=timeout or slow
This example allows up to 128 simultaneous downloads. Note that this is likely to crash remote web servers - or at least fail to download many of the files - because of limits on the number of simultaneous sessions at many sites. At busy times of day, you might want to lower this to 1 or 2, especially at sites that limit the number of simultaneous users. Otherwise you will not get all of the downloads.
httrack http://www.shoesizes.com -O /tmp/shoesizes -c128
Many operating systems have a limit of 64 file handles, including internet connections and all other files that can be opened. Therefore, in many cases, more that 48 connections might cause a "socket error" because the OS can not handle that many sockets. This is also true for many servers. As an example, a test with 48 sockets on a cgi-based web server (Pentium 166,80Meg RAM) overloaded the machine and stopped other services from running correctly. Some servers will ban users that try to brutally download the website. 8 sockets is generally good, but when I'm getting large files (e.g., from a a site with large graphical images) 1 or 2 sockets is a better selection. Here are some other figures from one sample set of runs:
Tests: on a 10/100Mbps network, 30MB website, 99 files (70 images (some are little, other are big (few MB)), 23 HTML) With 8 sockets: 1,24MB/s With 48 sockets: 1,30MB/s With 128 sockets: 0,93MB/s
The timeout option causes downloads to time out after a non-response from a download attempt. 30 seconds is pretty reasonable for many sites. You might want to increase the number of retries as well so that you try again and again after such timeouts.
httrack http://www.shoesizes.com -O /tmp/shoesizes -%c20
This limits the number of connections per second. It is similar to the above option but allows the pace to be controlled rather than the simultanaety. It is particulsrly useful for long-term pulls at low rates that allow little impact on remote infrastructure. The default is 10 connections per second.
httrack http://www.shoesizes.com -O /tmp/shoesizes -T30
This example increases the number of retries to 5. This means that if a download fails 5 times, httrack will give up on it. For relatively unreliable sites - or for busy times of day, this number should be higher.
httrack http://www.shoesizes.com -O /tmp/shoesizes -R5
This is an interesting option. It says that in a traffic jam - where downloads are excessively slow - we might decide to back off the download. In this case, we have limited downloads to stop bothering once we reach 10 bytes per second.
httrack http://www.shoesizes.com -O /tmp/shoesizes -J10
These three options will cause the download from a host to be abandoned if (respectively) (0) never, (1) a timeout is reached, (2) slow traffic is detected, (or) (3) a timeout is reached OR slow traffic is detected.
httrack http://www.shoesizes.com -O /tmp/shoesizes -H0 httrack http://www.shoesizes.com -O /tmp/shoesizes -H1 httrack http://www.shoesizes.com -O /tmp/shoesizes -H2 httrack http://www.shoesizes.com -O /tmp/shoesizes -H3
Of course these options can be combined to provide a powerful set of criteria for when to continue a download and when to give it up, how hard to push other sites. and how much to stress infrastructures.
Link Following Options
Links options: %P *extended parsing, attempt to parse all links, even in unknown tags or Javascript (%P0 don't use) n get non-html files 'near' an html file (ex: an image located outside) t test all URLs (even forbidden ones) %L add all URL located in this text file (one URL per line)
The links options allow you to control what links are followed and what links are not as well as to provide long lists of links to investigate. Any setting other than the default for this option forces the engine to use less reliable and more complex parsing. 'Dirty' parsing means that links like 'xsgfd syaze="foo.gif"' will cause HTTrack to download foo.gif, even if HTTrack don't know what the "xsgfd syaze=" tag actually means! This option is powerful because some links might otherwise be missed, but it can cause errors in HTML or javascript.
This will direct the program to NOT search Javascript for unknown tag fields (e.g., it will find things like foo.location="bar.html"; but will not find things like bar="foo.gif";). While I have never had a reason to use this, some users may decide that they want to be more conservative in their searches. As a note, javascript imported files (.js) are not currently searched for URLs.
httrack http://www.shoesizes.com -O /tmp/shoesizes '%P0'
Now here is a classic bit of cleaverness that 'does the right thing' for some cases. In this instance, we are asking httrack to get images - like gif and jpeg files that are used by a web page in its display, even though we would not normally get them. For example, if we were only getting a portion of a web site (e.g., everything under the 'bob directory') we might want to get graphics from the rest of the web sote - or the rest of the web - that are used in those pages as well so that our mirror will look right.
httrack http://www.shoesizes.com -O /tmp/shoesizes -n
Here, we limit the collection to bob's area of the server - except that we get images and other such things that are used by bob in his area of the server.
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -n
This option 'tests' all links - even those forbidden (by the robot exclusion protocol) - by using the 'HEAD' protocol to test for the presence of a file.
httrack http://www.shoesizes.com/ -O /tmp/shoesizes -t
In this case, we use a file to list the URLs we wish to mirror. This is particularly useful when we have a lot to do and don't want to tirelessly type in URLs on command line after command line. It's also useful - for example - if you update a set of mirrored sites evey evening. You can set up a command like this to run automatically from your cron file.
httrack -%L linkfile -O /tmp/shoesizes
This will update the mirror of your list of sites whenever it is run.
httrack -%L linkfile -O /tmp/shoesizes -B --update
The link file is also useful for things like this example where, after a binary image of a hard disk was analyzed (image) URLs found on that disk were collected by httrack:
strings image | grep "http://" > list; httrack -%L list -O /tmp/shoesizes
Mirror Build Options
Build options: NN name conversion type (0 original structure, 1+: see below) N user defined structure (-N "%h%p/%n%q.%t") LN long names (L1 long names / L0 8-3 conversion) K keep original links (e.g. http://www.adr/link) (K0 relative link) x replace external html links by error pages o generate output html file in case of error (404..) (o0 don't generate) X purge old files after update (X0 keep delete) %x do not include any password for external password protected websites (%x0 include) (--no-passwords) %q include query string for local files (information only) (%q0 don't include) (--include-query-string)
The user can define naming conventions for building the mirror of a site by using these options. For example, to retain the original structure, the default is used. This only modifies the structure to the extent that select characters (e.g., ~, :, <, >, \, and @) are replaced by _ in all pathnames.
httrack http://www.shoesizes.com -O /tmp/shoesizes -N0
OR
httrack http://www.shoesizes.com -O /tmp/shoesizes
In either case, the mirror will build with the same directory hierarchy and name structure as the original site. For cases when you want to define your own structure, you use a string like this:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -N "%h%p/%n.%t"
In this case, %h, %p, $n, and %t stand for the href element (e.g., http://www.shoesizes.com or ftp://ftp.shoesizes.com), %p stands for the pathname (e.g., /bob/), %n stands for the name of the file, and %t stands for type (file extension). The full list of these options follows:
%n Name of file without file type (ex: image) %N Name of file, including file type (ex: image.gif) %t File type (ex: gif) %p Path [without ending /] (ex: /someimages) %h Host name (ex: www.all.net) %M URL MD5 (128 bits, 32 ascii bytes) %Q query string MD5 (128 bits, 32 ascii bytes) %q small query string MD5 (16 bits, 4 ascii bytes) %s? Short name version (ex: %sN)
Other 'N' options include:
Details: Option N N0 Site-structure (default) N1 HTML in web/, images/other files in web/images/ N2 HTML in web/HTML, images/other in web/images N3 HTML in web/, images/other in web/ N4 HTML in web/, images/other in web/xxx, where xxx is the file extension(all gif will be placed onto web/gif, for example) N5 Images/other in web/xxx and HTML in web/HTML N99 All files in web/, with random names (gadget !) N100 Site-structure, without www.domain.xxx/ N101 Identical to N1 exept that "web" is replaced by the site's name N102 Identical to N2 exept that "web" is replaced by the site's name N103 Identical to N3 exept that "web" is replaced by the site's name N104 Identical to N4 exept that "web" is replaced by the site's name N105 Identical to N5 exept that "web" is replaced by the site's name N199 Identical to N99 exept that "web" is replaced by the site's name N1001 Identical to N1 exept that there is no "web" directory N1002 Identical to N2 exept that there is no "web" directory N1003 Identical to N3 exept that there is no "web" directory (option set for g option) N1004 Identical to N4 exept that there is no "web" directory N1005 Identical to N5 exept that there is no "web" directory N1099 Identical to N99 exept that there is no "web" directory
Long names are normally used (the -L0 option) but if you are imaging to a DOS file system or want accessibility from older versions of DOS and Windows, you can use the -L1 option to generate these filename sizes.
httrack http://www.shoesizes.com -O /tmp/shoesizes -L1
With the 'K' option, you can keep the original links in files. While this is less useful in being able to view a web site froim the mirrored copy, it is vitally important if you want an accurate copy of exactly what was on the web site in the first place. In a forensic image, for example, you might want to use this option to prevent the program from modifying the data as it is collected.
httrack http://www.shoesizes.com -O /tmp/shoesizes -K
In this case, instead of leaving external links (URLs that point to sites not being mirrored) in the pages, these links are replaced by pages that leave messages indicating that they could not be found. This is useful for local mirrors not on the Internet or mirrors that are on the Internet but that are not supposed to lead users to external sites. A really good use for this is that 'bugging' devices placed in web pages to track who is using them and from where will be deactivated byt his process.
httrack http://www.shoesizes.com -O /tmp/shoesizes -x
This option prevents the generation of '404' error files to replace files that were not found even though there were URLs pointing to them. It is useful for saving space as well as eliminating unnecessary files in operations where a working web site is not the desired result.
httrack http://www.shoesizes.com -O /tmp/shoesizes -o0
This option prevents the authoatic purging of files from the mirror site that were not found in the original web site after an 'update' is done. If you want to retain old data and old names for files that were renamed, this option should be used. If you want an up-to-date reflection of the current web site, you should not use this option.
httrack http://www.shoesizes.com -O /tmp/shoesizes -X0
These options can be combined as desired to produce a wide range of different arrangements, from collections of only graphical files stored in a graphics area, to files identified by their MD5 checksums only, all stored in the same directory.
httrack http://www.shoesizes.com -O /tmp/shoesizes %x0 include
This will not include passwords for web sites. If you mirror http://smith_john:foobar@www.privatefoo.com/smith/, and exclude using filters some links, these links will be by default rewritten with password data. For example, "bar.html" will be renamed into http://smith_john:foobar@www.privatefoo.com/smith/bar.html This can be a problem if you don't want to disclose the username/password! The %x option tell the engine not to include username/password data in rewritten URLs.
httrack http://www.shoesizes.com -O /tmp/shoesizes %q
This option is not very useful, because parameters are useless, as pages are not dynamic anymore when mirrored. But some javascript code may use the query string, and it can give useful information. For example: catalog4FB8.html?page=computer-science is clearer than catalog4FB8.html Therefore, this option is activated by default.
Spider Options
These options provide for automation with regard to the remote server. For example, some sites require that cookies be accepted and sent back in order to allow access.
Spider options: bN accept cookies in cookies.txt (0=do not accept, 1=accept) u check document type if unknown (cgi,asp..) (u0 don't check, u1 check but /, u2 check always) j parse Java Classes (j0 don't parse) sN follow robots.txt and meta robots tags (0=never,1=sometimes, 2=always) %h force HTTP/1.0 requests (reduce update features, only for old servers or proxies) %B tolerant requests (accept bogus responses on some servers, but not standard!) %s update hacks: various hacks to limit re-transfers when updating %A assume that a type (cgi,asp..) is always linked with a mime type (-%A php3=text/html) (--assume )
By default, cookies are universally accepted and returned. This makes for more effective collection of data, but allows the site to be identified with its collection of data more easily. To disable cookies, use this option:
httrack http://www.shoesizes.com -O /tmp/shoesizes -b0
Some documents have known extension types (e.g., html), while others have unknown types (e.g., iuh87Zs) and others may have misleading types (e.g., an html file with a 'gif' file extension. These options provide for (0) not checking file types, (1) checking all file types except directories, and (2) checking all file types including directories. Choose from these options:
httrack http://www.shoesizes.com -O /tmp/shoesizes -u0 httrack http://www.shoesizes.com -O /tmp/shoesizes -u1 httrack http://www.shoesizes.com -O /tmp/shoesizes -u2
Meta tags or 'robots.txt' files on a web site are used to indicate what files should and should not be visited by automatic programs when collectiong data. The polite and prudent move for normal data collection (and the default) is to follow this indication:
httrack http://www.shoesizes.com -O /tmp/shoesizes -s2
This follows the robots protocol and meta-tags EXCEPT in cases where the filters disagree with the robots protocols or meta-tags.
httrack http://www.shoesizes.com -O /tmp/shoesizes -s1
In this next case, we ignore meta-tags and robots.txt files completely and just take whatever we can get from the site. The danger of this includes the fact that automated programs - like games or search engines may generate an unlimited number of nearly identical or identical outputs that will put us in an infinite loop collecting useless data under different names. The benefit is that we will get all the data there is to get.
httrack http://www.shoesizes.com -O /tmp/shoesizes -s0
This next option uses strict HTTP/1.0 protocol. This means the program will use HTTP/1.0 headers (as in RFC1945.TXT) and NOT extended 1.1 features described in RFC2616.TXT. For example, reget (complete a partially downloaded file) is a HTTP/1.1 feature. The Etag feature is also a HTTP/1.1 feature (Etag is a special identifier that allow to easily detect file changes).
httrack http://www.shoesizes.com -O /tmp/shoesizes -%h
Some servers give responses not strictly within the requirements of the official http protocol. These 'Bogus' responses can be accepted by using this option. For example, when requesting foo.gif (5132 bytes), the server can, optionally, add: Content-length: 5132
This helps the client by allowing it to reserve a block of memory, instead of collecting each byte and re-reserving memory each time data is being received. But some servers are bogus, and send a wrong filesize. When HTtrack detects the end of file (connection broken), there are three cases:
1- The connection has been closed by the server, and we have received all data (we have received the number of bytes incicated by the server). This is fine because we have successfully received the file.
2- The connection has been closed by the server, BUT the filesize received is different from the server's headers: the connection has been suddenly closed, due to network problems, so we reget the file
3- The connetion has been closed by the server, the filesize received is different from the server's headers, BUT the file is complete, because the server gave us a WRONG information! In this case, we use the bogus server option:
httrack http://www.shoesizes.com -O /tmp/shoesizes -%B
These options can be combined for the particular needs of the situaiton and are often adapted as a result of site-specific experiences.
httrack http://www.shoesizes.com -O /tmp/shoesizes -%s
This is a collection of "tricks" which are not really "RFC compliant" but which can save bandwidth by trying not to retransfer data in several cases.
httrack http://www.shoesizes.com -O /tmp/shoesizes -%A asp=text/html
The most important new feature for some people, maybe. This option tells the engine that if a link is en countered, with a specific type (.cgi, .asp, or .php3 for example), it MUST assume that this link has always the same MIME type, for example the "text/html" MIME type. This is VERY important to speed up many mirrors.
We have done tests on big HTML files (approx. 150 MB, 150,000,000 bytes!) with 100,000 links inside. Such files are being parsed in approx. 20 seconds on my own PC by the latest optimized releases of HTTra ck. But these tests have been done with links of known types, that is, html, gif, and so on.. If you have, say, 10,000 links of unknown type, such as ".asp", this will cause the engine to test ALL t hese files, and this will SLOOOOW down the parser. In this example, the parser will take hours, instead of 20 seconds! In this case, it would be great to tell HTTrack: ".asp pages are in fact HTML pages" This is possible, using: -%A asp=text/html
The -%A option can be replaced by the alias --assume asp=text/html which is MUCH more clear. You can use multiple definitions, separed by ",", or use multiple options. Therefore, these two lines are identical:
--assume asp=text/html --assume php3=text/html --assume cgi=image/gif --assume asp=text/html,php3=text/html,cgi=image/gif
The MIME type is the standard well known "MIME" type. Here are the most important ones: text/html Html files, parsed by HTTrack image/gif GIF files image/jpeg Jpeg files image/png PNG files
There is also a collection of "non standard" MIME types. Example:
application/x-foo Files with "foo" type
Therefore, you can give to all files terminated by ".mp3" the MIME type: application/x-mp3
This allow you to rename files on a mirror. If you KNOW that all "dat" files are in fact "zip" files ren amed into "dat", you can tell httrack:
--assume dat=application/x-zip
You can also "name" a file type, with its original MIME type, if this type is not known by HTTrack. This will avoid a test when the link will be reached:
--assume foo=application/foobar
In this case, HTTrack won't check the type, because it has learned that "foo" is a known type, or MIME type "application/foobar". Therefore, it will let untouched the "foo" type.
A last remark, you can use complex definitions like:
--assume asp=text/html,php3=text/html,cgi=image/gif,dat=application/x-zip,mpg=application/x-mp3,application/foobar
..and save it on your .httrackrc file:
set assume asp=text/html,php3=text/html,cgi=image/gif,dat=application/x-zip,mpg=application/x-mp3,application/foobar
Browser Options
Browsers commonly leave footprints in web servers - as web servers leave footprints in the browser.
Browser ID: F user-agent field (-F "user-agent name") %F footer string in Html code (-%F "Mirrored [from host %s [file %s [at %s]]]" %l preffered language (-%l "fr, en, jp, *" (--language )
The user-agent field is used by browsers to determine what kind of browser you are using as well as other information - such as your system type and operating system version. The 'User Agent' field can be set to indicate whatever is desired to the server. In this case, we are claiming to be a netscape browser (version 1.0) running a non-exitent Solaris operating system version on a Sun Sparcstation.
httrack http://www.shoesizes.com -O /tmp/shoesizes -F "Mozilla 1.0, Sparc, Solaris 23.54.34"
On the other side, we may wish to mark each page collected with footer information so that we can see from the page where it was collected from, when, and under what name it was stored.
httrack http://www.shoesizes.com -O /tmp/shoesizes -%F "Mirrored [from host %s [file %s [at %s]]]"
This makes a modified copy of the file that may be useful in future identification. While it is not 'pure' in some senses, it may (or may not) be considered siilar to a camera that adds time and date stamps from a legal perspective.
httrack http://www.shoesizes.com -O /tmp/shoesizes -%l "fr, en, jp, *"
"I prefer to have pages with french language, then english, then japanese, then any other language"
Log, Cache, and Index Options
A lot of options are available for log files, indexing of sites, and cached results:
Log, index, cache C create/use a cache for updates and retries (C0 no cache,C1 cache is prioritary, C2 test update before) k store all files in cache (not useful if files on disk) %n do not re-download locally erased files Q log quiet mode (no log) q quiet mode (no questions) z extra infos log Z debug log v verbose screen mode %v display on screen filenames downloaded (in realtime) (--display) f log file mode f2 one single log file (--single-log) I make an index (I0 don't make) %I make an searchable index for this mirror (* %I0 don't make) (--search-index)
A cache memory area is used for updates and retries to make the process far more efficient than it would otherwise be. You can choose to (0) go without a cache, (1) do not check remotly if the file has been updated or not, just load the cache content, or (2) see what works best and use it (the default). Here is the no cache example.
httrack http://www.shoesizes.com -O /tmp/shoesizes -C0
The cache can be used to store all files - if desired
- but if files are being stored on disk anyway (the normal process for a mirroring operation), this is not helpful.
httrack http://www.shoesizes.com -O /tmp/shoesizes -k
In some cases, a file from a mirror site is erased locally. For example, if a file contains inappropriate content, it may be erased from the mirror site but remain on the remote site. This option allows you to leave deleted files permanently deleted when you do a site update.
httrack http://www.shoesizes.com -O /tmp/shoesizes -update '%n'
If no log is desired, the following option should be added.
httrack http://www.shoesizes.com -O /tmp/shoesizes -Q
If no questions should be asked of the user (in a mode that would otherwise ask questions), the following option should be added.
httrack http://www.shoesizes.com -O /tmp/shoesizes -q
By adding these options, you get (-z) extra log information or (-Z) debugging information, and (-v) verbose screen output.
httrack http://www.shoesizes.com -O /tmp/shoesizes -z -Z -v
Multiple log files can be created, but by default, this option is used to put all logs into a single log file.
httrack http://www.shoesizes.com -O /tmp/shoesizes -f2
Finally, an index is normally made of the sites mirrored (a pointer to the first page found from each specified URL) in an index.html file in the project directory. This can be prevented through the use of this option:
httrack http://www.shoesizes.com -O /tmp/shoesizes -I0
httrack http://www.shoesizes.com -O /tmp/shoesizes %v
Animated information when using consol-based version, example: 17/95: localhost/manual/handler.html (6387 bytes) - OK
httrack http://www.shoesizes.com -O /tmp/shoesizes f2
Do not split error and information log (hts-log.txt and hts-err.txt) - use only one file (hts-log.txt)
httrack http://www.shoesizes.com -O /tmp/shoesizes -%I linux.localdomain
Still in testing, this option asks the engine to generate an index.txt, useable by third-party programs or scripts, to index all words contained in html files. The above example will produce index.txt:
.. abridged 1 linux/manual/misc/API.html =1 (0) absence 3 linux/manual/mod/core.html 2 linux/manual/mod/mod_imap.html 1 linux/manual/misc/nopgp.html 1 linux/manual/mod/mod_proxy.html 1 linux/manual/new_features_1_3.html =8 (0) absolute 3 linux/manual/mod/mod_auth_digest.html 1 linux/manual/mod/mod_so.html =4 (0) ..
Expert User Options
For expert users, the following options provide further options.
Expert options: pN priority mode: ( p3) 0 just scan, don't save anything (for checking links) 1 save only html files 2 save only non html files 3 save all files 7 get html files before, then treat other files S stay on the same directory D can only go down into subdirs U can only go to upper directories B can both go up&down into the directory structure a stay on the same address d stay on the same principal domain l stay on the same location (.com, etc.) e go everywhere on the web %H debug HTTP headers in logfile
One interesting application allows the mirror utility to check for valid and invalid links on a site. This is commonly used in site tests to look for missing pages or other html errors. I often run such programs against my web sites to verify that nothing is missing.
httrack http://www.shoesizes.com -O /tmp/shoesizes -p0
To check for valid links outside of a site, the '-t' option can be used:
httrack http://www.shoesizes.com -O /tmp/shoesizes -t
These options can be combined, for example, to provide a service that checks sites for validity of links and reports back a list of missing files and statistics.
Other options allow the retention of select files - for example - (1) only html files, (2) only non-html files, (3) all files, and (7) get all html files first, then get other files. This last option provides a fast way to get the web pointers so that, for example, a time limited collection process will tend to get the most important content first.
In many cases, we only want the files froma given directory. In this case, we specify this option:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -S
This option allows the mirror to go only into subdirectories of the initial directory on the remote host. You might want to combine it with the -n option to get all non-html files linked from the pages you find.
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -D -n
If you only want to work your way up the directory structure from the specified URL (don't ask me why you might want to do this), the following command line is for you:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -U
If you want to go both up and down the directory structure (i.e., anywhere on on this site that the requested page leads you to), this option will be best:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -B
The default is to remain on the same IP address - or host name. This option specifes this explicitly:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -a
If you want to restrict yourself only to the same principal domain (e.g., include sites liks ftp.shoesizes.com), you would use this option.
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -d
To restrict yourself to the same major portion of the Internet (e.g., .com, .net, .edu, etc.) try this option:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -l
Finally, if you want to mirror the whole Internet - at least every place on the internet that is ever led to - either directly or indirectly - from the starting point, use this one... Please note that this will almost always run you out of resources unless you use other options - like limiting the depth of search.
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -e
Last but not least, you can include debugging informaiton on all headers from a collection process by using this option:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -'%H'
The options S, D, U, B, a, d, l, and e can be replaces with filter options approximately as follows:
S -www.foo.com/ +www.foo.com/bar/[file] D (default) U +www.foo.com/bar/ -www.foo.com/[name]/ B +www.foo.com/bar/ a (default) d +[name].foo.com/ l +[name].com/ e +* (this is crazy unless a depth limit is used!)
Guru Options - DO NOT USE!!!
This is a new section, for all "not very well documented options". You can use them, in fact, do not believe what is written above!
#0 Filter test (-#0 '*.gif' 'www.bar.com/foo.gif')
To test the filter system. Example:
$ httrack -#0 'www..com/foobar.gif' 'www.mysite.com/test/foo4bar.gif' www.mysite.com/test/foo4bar.gif does match www..com/foobar.gif
#f Always flush log files
Useful if you want the hts-log.txt file to be flushed regularly (not buffered)
#FN Maximum number of filters
Use if if you want to use more than the maximum default number of filters, that is, 500 filters: -#F2000 for 2,000 filters
#h Version info
Informations on the version number
#K Scan stdin (debug)
Not useful (debug only)
#L Maximum number of links (-#L1000000)
Use if if you want to use more than the maximum default number of links, that is, 100,000 links: -#L2000000 for 2,000,000 links
#p Display ugly progress information
Self-explanatory :) I will have to improve this one
#P Catch URL
"Catch URL" feature, allows to setup a temporary proxy to capture complex URLs, often linked with POST action (when using form based authentication)
#R Old FTP routines (debug)
Debug..
#T Generate transfer ops. log every minutes
Generate a log file with transfer statistics
#u Wait time
"On hold" option, in seconds
#Z Generate transfer rate statictics every minutes
Generate a log file with transfer statistics
#! Execute a shell command (-#! "echo hello")
Debug..
Command-line Specific Options
Command-line specific options: V execute system command after each files ($0 is the filename: -V "rm \$0") (--userdef-cmd )
This option is very nice for a wide array of actions that might be based on file details. For example, a simple log of all files collected could be generated by using:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes -V "/bin/echo \$0"
%U run the engine with another id when called as root (-%U smith) (--user )
Change the UID of the owner when running as r00t
Details: User-defined option N %[param] param variable in query string
This new option is important: you can include query-string content when forming the destination filename!
Example: you are mirroring a huge website, with many pages named as: www.foo.com/catalog.php3?page=engineering www.foo.com/catalog.php3?page=biology www.foo.com/catalog.php3?page=computing ..
Then you can use the -N option:
httrack www.foo.com -N "%h%p/%n%[page].%t"
If found, the "page" parameter will be included after the filename, and the URLs above will be saved as:
/home/mywebsites/foo/www.foo.com/catalogengineering.php3 /home/mywebsites/foo/www.foo.com/catalogbiology.php3 /home/mywebsites/foo/www.foo.com/catalogcomputing.php3 ...
Shortcuts
These options provide shortcust to combinations of other options that are commonly used.
Shortcuts: --mirror *make a mirror of site(s) (default) --get get the files indicated, do not seek other URLs (-qg) --list add all URL located in this text file (-%L) --mirrorlinks mirror all links in 1st level pages (-Y) --testlinks test links in pages (-r1p0C0I0t) --spider spider site(s), to test links: reports Errors & Warnings (-p0C0I0t) --testsite identical to --spider --skeleton make a mirror, but gets only html files (-p1) --update update a mirror, without confirmation (-iC2) --continue continue a mirror, without confirmation (-iC1) --catchurl create a temporary proxy to capture an URL or a form post URL --clean erase cache & log files --http10 force http/1.0 requests (-%h)
Mirror is the default behavior. It is detailed earlier.
get simply gets the files specified on the command line.
The list option is useful for including a list of sites to collect data from.
The mirrorlinks option is ideal for using the result of a previous search (like a list of pages found in a web search or somebody's URL collection) to guide the collection of data. With additional options (such as depth 1) it can be used to collect all of the pages linked to a given page without going further. Here is an example:
httrack http://www.shoesizes.com/bob/ -O /tmp/shoesizes --mirrorlinks -e -r1
Testing links in pages is useful for automating the verification that a link from a file is not pointing to a non-existent page.
The spider option does a site test automatically and returns errors for broken links.
The skeleton option makes a mirror of html files only.
The update option updates a site to match a remote mirror.
The continue option continues a previously terminated mirroring activity. This is useful for all sorts of mirror failures.
The catchurl option is a small application designed to catch difficult pages, like sites protected via formulas. You can see at http://httrack.free.fr/HelpHtml/addurl.html a Windows description of this application. The purpose is to create a temporary proxy, that will catch the user request to a page, and then store this request to continue the mirror. For example,
- browse www.foo.com/bar/ until you have a page with a form
- fill this form to enter the site BUT do not click "submit"
- start the --catchurl application
- change your browser proxy settings according to the --catchurl application
- click on "submit" on your browser
- HTTrack has now captured this click and has stored it
- restore your proxy settings
- (click back in your browser)
The clean option erases cache and log files.
The http10 option forces http/1.0 requests (the same as -%h).
Filters
Filters are normally placed at the end of the command line, but can be intermixed with other command line options if desired, except that if they are placed between (for example) the '-O' and the pathname, your results may be different than you might otherwise predict. There are two sorts of filters, filters that indicate what to include (+) and filters that indicate what to exclude (-).
Starting with the initially specified URLs, the default operation mode is to mirror starting from these URLs downward into the directory structure of the host (i.e. if one of your starting pagees was www.all.net/test/a.html, all links starting with www.all.net/test/ will be collected but links in www.all.net/anything-else will not be collected, because they are in a higher directory strcuture level. This prevents HTTrack from mirroring the whole site. If you may want to download files are in other parts of the site or pf particular types - or to not download files in a particular part of the site or of a particular type, you can use filters to specify more precisely what to collect and what not to collect.
The syntax for filters is similar to Unix regular expressions. A simple filter can be made by using characters from the URL with '*' as a wildcard for 0 or more characters - with the last filter rule having the highest precendence. An initial '+' indicates URLs to include and an initial '-' indicated URLs to not include. For example:
'-' '+jpg'
would only get files ending in the 'jpg' extension, while:
'-*jpg'
would not get any files ending in the jpg extension. You can add more filter lines to restrict or expand the scope as desired. The last rule is checked first, and so on - so that the rules are in reverse priority order. Here's an example:
+*.gif -image*.gif
Will accept all gif files BUT image1.gif,imageblue.gif,imagery.gif and so on
-image*.gif +*.gif
Will accept all gif files, because the second pattern is prioritary (because it is defined AFTER the first one)
The full syntax for filters follows:
*
any characters (the most commonly used)
*[file] or *[name]
any filename or name, e.g. not /,? and ; characters
*[path]
any path (and filename), e.g. not ? and ; characters
*[a,z,e,r,t,y]
any letters among a,z,e,r,t,y
*[a-z]
any letters
*[0-9,a,z,e,r,t,y]
any characters among 0..9 and a,z,e,r,t,y
*[]
no characters must be present after
*[< NN] size less than NN Kbytes
*[> PP] size more than PP Kbytes
*[< NN > PP] size less than NN Kbytes and more than PP Kbytes
Here are some examples of filters: (that can be generated automatically using the interface)
-www.all.net*
This will refuse/accept this web site (all links located in it will be rejected)
+*.com/*
This will accept all links that contains .com in them
-*cgi-bin*
This will refuse all links that contains cgi-bin in them
+*.com/*[path].zip
This will accept all zip files in .com addresses
-*someweb*/*.tar*
This will refuse all tar (or tar.gz etc.) files in hosts containing someweb
+*/*somepage*
This will accept all links containing somepage (but not in the address)
-*.html
This will refuse all html files from anywhere in the world.
+*.html*[]
Accept *.html, but the link must not have any supplemental characters
at the end(e.g., links with parameters, like www.all.net/index.html?page=10
will not match this filter)
-.gif[> 5] -.zip +.zip*[< 10] refuse all gif files smaller than 5KB, exlude all zip files, EXCEPT zip files smaller than 10KB
User Authentication Protocols
Smoe servers require user ID and password information in order to gain access. In this example, the user ID smith with password foobar is accessing www.all.net/private/index.html
httrack smith:foobar@www.all.net/private/index.html
For more advanced forms of authentication, such as those involving forms and cookies of various sorts, an emerging capability is being provided through th URL capture features (--catchurl). This feature don't work all of the time.
.httrackrc
A file called '.httrackrc' can be placed in the current directory, or if not found there, in the home directory, to include command line options. These options are included whenever httrack is run. A sample .httrack follows:
set sockets 8 set retries 4 index on set useragent "Mozilla [en] (foo)" set proxy proxy:8080
But the syntax is not strict, you can use any of these:
set sockets 8 set sockets=8 sockets=8 sockets 8
.httrackrc is sought in the following sequence with the first occurence used:
in the dirctory indicated by -O option (.httrackrc) in the current directory (.httrackrc) in the user's home directory (.httrackrc) in /etc/httrack.conf (named httrack.conf to be "standard")
An example .httrackrc looks like:
set sockets=8 set index on retries=2 allow .gif deny ad.doubleclick.net/
Each line is composed of an option name and a parameter. The "set" token can be used, but is not mandatory (it is ignored, in fact). The "=" is also optionnal, and is replaced by a space internally. The "on" and "off" are the same as "1" and "0" respectively. Therefore, the example .httrackrc above is equivalent to:
sockets=8 index=1 retries=2 allow=.gif deny=ad.doubleclick.net/
Because the "=" seems to (wrongly) imply a variable assignment (the option can be defined more than once to define more than one filter) the following .httrackrc:
allow .gif allow .jpg
looks better for a human than:
allow=.gif allow=.jpg
Here's a example run with the example .httrackrc file:
$ httrack ghost $ cat hts-cache/doit.log -c8 -C1 -R2 +.gif -ad.doubleclick.net/ ghost
The "-c8 -C1 -R2 +.gif -ad.doubleclick.net/" was added by the .httrackrc
Release Notes
Some things change between releases. Here are some recent changes in httrack that may affect some of these options:
Options S,D,U,B, and a,d,l,e are default behaviours of HTTrack. they were the only options in old versions (1.0). With the introduction of filters, their roles are now limited, because filters can override them.
Note for the -N option: "%h%p/%n%q.%t" will be now be used if possible. In normal cases, when a file does not have any parameters (www.foo.com/bar.gif) the %q option does not add anything, so there are no differences in file names. But when parameters are present (for example, www.foo.com/bar.cgi?FileCollection=133.gif), the additionnal query string (in this case, FileCollection=133.gif) will be "hashed" and added to the filename. For example:
'www.all.net/bar.cgi?FileCollection=133.gif' will be named '/tmp/mysite/bar4F2E.gif'
The additionnal 4 letters/digits are VERY useful in cases where there are a substantial number of identical files:
www.all.net/bar.cgi?FileCollection=133.gif www.all.net/bar.cgi?FileCollection=rose.gif www.all.net/bar.cgi?FileCollection=plant4.gif www.all.net/bar.cgi?FileCollection=silver.gif and so on...
In these cases, there is a small probability of a hash collision forlarge numbers of files.
Some More Examples
Here are some examples of special purpose httrack command lines that might be useful for your situation.
This is a 'forensic' dump of a web site - intended to collect all URLs reachable from the initial point and at that particular site. It is intended to make no changes whatsoever to the image. It also prints out an MD5 checksum of each file imaged so that the image can be verified later to detect and changes after imaging. It uses 5 retries to be more certain than normal of getting the files, never abandons its efforts, keeps original links, does not generate error files, ignores site restrictions for robots, logs as much as it can, stays in the principal domain, places debugging headers in the log file,
httrack "www.website.com/" -O "/tmp/www.website.com" -R5H0Ko0s0zZd %H -V "md5 \$0" "+.website.com/"
Here's an example of a site where I pulled a set of data related to some subject. In this case, I only wanted the relevant subdirectory, all external links were to remain the same, a verbose listing of URLs was to be printed, and I wanted files near (n) and below (D) the original directory. Five retries just makes sure I don't miss anything.
httrack "http://www.somesite.com/~library/thing/thingmain.htm" -O /tmp/thing -R5s0zZvDn
This listing is, of course, rather verbose. To reduce the noise, you might want to do something more like this:
httrack "http://www.somesite.com/~library/thing/thingmain.htm" -O /tmp/thing -R5s0zvDn
A still quieter version - without any debugging information but with a list of files loaded looks like this:
httrack "http://www.somesite.com/~library/thing/thingmain.htm" -O /tmp/thing -R5s0vDn
For the strong silent type, this might be still better:
httrack "http://www.somesite.com/~library/thing/thingmain.htm" -O /tmp/thing -R5s0qDn
General questions:
Q: The install is not working on NT without administrator rights!
A: That's right. You can, however, install WinHTTrack on your own machine, and then copy your WinHTTrack folder from your Program Files folder to another machine, in a temporary directory (e.g. C:\temp)
Q: Where can I find French/other languages documentation?
A: Windows interface is available on several languages, but not yet the documentation!
Q: Is HTTrack working on NT/2000?
A: Yes, it should
Q: What's the difference between HTTrack and WinHTTrack?
A: WinHTTrack is the Windows release of HTTrack (with a graphic shell)
Q: Is HTTrack Mac compatible?
A: No, because of a lack of time. But sources are available
Q: Can HTTrack be compiled on all Un*x?
A: It should. The Makefile may be modified in some cases, however
Q: I use HTTrack for professional purpose. What about restrictions/license fee?
A: There is no restrictions using HTTrack for professional purpose, except if you want to sell a product including HTTrack components (parts of the source, or any other component). See the license.txt file for more informations
Q: Is a DLL/library version available?
A: Not yet. But, again, sources are available (see license.txt for distribution infos)
Q: Is there a X11/KDE shell available for Linux and Un*x?
A: No. Unfortunately, we do not have enough time for that - if you want to help us, please write one!
Troubleshooting:
Q: Only the first page is caught. What's wrong? A: First, check the hts-err.txt error log file - this can give you precious informations.
The problem can be a website that redirects you to another site (for example, www.all.net to public.www.all.net) : in this case, use filters to accept this site
This can be, also, a problem in the HTTrack options (link depth too low, for example)
Q: With WinHTTrack, sometimes the minimize in system tray causes a crash!
A: This bug sometimes appears in the shell on some systems. If you encounter this problem, avoid minimizing the window!
Q: Files are created with strange names, like '-1.html'!
A: Check the build options (you may have selected user-defined structure with wrong parameters!)
Q: When capturing real audio links (.ra), I only get a shortcut!
A: Yes. The audio/video realtime streaming capture is not yet supported
Q: Using user:password@address is not working!
A: Again, first check the hts-err.txt error log file - this can give you precious informations
The site may have a different authentication scheme (form based authentication, for example)
Q: When I use HTTrack, nothing is mirrored (no files) What's happening?
A: First, be sure that the URL typed is correct. Then, check if you need to use a proxy server (see proxy options in WinHTTrack or the -P proxy:port option in the command line program). The site you want to mirror may only accept certain browsers. You can change your "browser identity" with the Browser ID option in the OPTION box. Finally, you can have a look at the hts-err.txt (and hts-log.txt) file to see what happened.
Q: There are missing files! What's happening?
A: You may want to capture files that are in a different folder, or in another web site. In this case, HTTrack does not capture them automatically, you have to ask it to do. For that, use the filters.
Example: You are downloading http://www.all.net/foo/ and can not get .jpg images located in http://www.all.net/bar/ (for example, http://www.all.net/bar/blue.jpg)
Then, add the filter rule +www.all.net/bar/*.jpg to accept all .jpg files from this location
You can, also, accept all files from the /bar folder with +www.all.net/bar/*, or only html files with +www.all.net/bar/*.html and so on..
Q: I'm downloading too many files! What can I do?
A: This is often the case when you use too large filters, for example +.html, which asks the engine to catch all .html pages (even ones on other sites!). In this case, try to use more specific filters, like +www.all.net/specificfolder/.html
If you still have too many files, use filters to avoid somes files. For example, if you have too many files from www.all.net/big/, use -www.all.net/big/* to avoid all files from this folder.
Q: File types are sometimes changed! Why?
A: By default, HTTrack tries to know the type of remote files. This is useful when links like http://www.all.net/foo.cgi?id=1 can be either HTML pages, images or anything else. Locally, foo.cgi will not be recognized as an html page, or as an image, by your browser. HTTrack has to rename the file as foo.html or foo.gif so that it can be viewed.
Sometimes, however, some data files are seen by the remote server as html files, or images : in this case HTTrack is being fooled.. and rename the file. You can avoid this by disabling the type checking in the option panel.
Q: I can not access to several pages (access forbidden, or redirect to another location), but I can with my browser, what's going on?
A: You may need cookies! Cookies are specific datas (for example, your username or password) that are sent to your browser once you have logged in certain sites so that you only have to log-in once. For example, after having entered your username in a website, you can view pages and articles, and the next time you will go to this site, you will not have to re-enter your username/password.
To "merge" your personnal cookies to an HTTrack project, just copy the cookies.txt file from your Netscape folder (or the cookies located into the Temporary Internet Files folder for IE) into your project folder (or even the HTTrack folder)
Q: Some pages can't be seen, or are displayed with errors!
A: Some pages may include javascript or java files that are not recognized. For example, generated filenames. There may be transfer problems, too (broken pipe, etc.). But most mirrors do work. We still are working to improve the mirror quality of HTTrack.
Q: Some Java applets do not work properly!
A: Java applets may not work in some cases, for example if HTTrack failed to detect all included classes or files called within the class file. Sometimes, Java applets need to be online, because remote files are directly caught. Finally, the site structure can be incompatible with the class (always try to keep the original site structure when you want to get Java classes)
If there is no way to make some classes work properly, you can exclude them with the filters. They will be available, but only online.
Q: HTTrack is being idle for a long time without transfering. What's happening?
A: Maybe you try to reach some very slow sites. Try a lower TimeOut value (see options, or -Txx option in the command line program). Note that you will abandon the entire site (except if the option is unchecked) if a timeout happen You can, with the Shell version, skip some slow files, too.
Q: I want to update a site, but it's taking too much time! What's happening?
A: First, HTTrack always tries to minimize the download flow by interrogating the server about the file changes. But, because HTTrack has to rescan all files from the begining to rebuild the local site structure, it can takes some time. Besides, some servers are not very smart and always consider that they get newer files, forcing HTTrack to reload them, even if no changes have been made!
Q: I am behind a firewall. What can I do?
A: You need to use a proxy, too. Ask your administrator to know the proxy server's name/port. Then, use the proxy field in HTTrack or use the -P proxy:port option in the command line program.
Q: HTTrack has crashed during a mirror, what's happening?
A: We are trying to avoid bugs and problems so that the program can be as reliable as possible. But we can not be infallible. If you occurs a bug, please check if you have the latest release of HTTrack, and send us an email with a detailed description of your problem (OS type, addresses concerned, crash description, and everything you deem to be necessary). This may help the other users too.
Q: I want to update a mirrored project, but HTTrack is retransfering all pages. What's going on?
A: First, HTTrack always rescan all local pages to reconstitute the website structure, and it can take some time. Then, it asks the server if the files that are stored locally are up-to-date. On most sites, pages are not updated frequently, and the update process is fast. But some sites have dynamically-generated pages that are considered as "newer" than the local ones.. even if there are identical! Unfortunately, there is no possibility to avoid this problem, which is strongly linked with the server abilities.
Questions concerning a mirror:
Q: I want to mirror a Web site, but there are some files outside the domain, too. How to retrieve them?
A: If you just want to retrieve files that can be reached through links, just activate the 'get file near links' option. But if you want to retrieve html pages too, you can both use wildcards or explicit addresses ; e.g. add www.all.net/* to accept all files and pages from www.all.net.
Q: I have forgotten some URLs of files during a long mirror.. Should I redo all?
A: No, if you have kept the 'cache' files (in hts-cache), cached files will not be retransfered.
Q: I just want to retrieve all ZIP files or other files in a web site/in a page. How do I do it?
A: You can use different methods. You can use the 'get files near a link' option if files are in a foreign domain. You can use, too, a filter adress: adding +*.zip in the URL list (or in the filter list) will accept all ZIP files, even if these files are outside the address.
Example : httrack www.all.net/someaddress.html +*.zip will allow you to retrieve all zip files that are linked on the site.
Q: There are ZIP files in a page, but I don't want to transfer them. How do I do it?
A: Just filter them: add -*.zip in the filter list.
Q: I don't want to load gif files.. but what may happen if I watch the page?
A: If you have filtered gif files (-*.gif), links to gif files will be rebuild so that your browser can find them on the server.
Q: I get all types of files on a web site, but I didn't select them on filters!
A: By default, HTTrack retrieves all types of files on authorized links. To avoid that, define filters like
- +
Example: httrack www.all.net/index.html - +www.all.net/.htm +www.all.net/.gif +www.all.net/*.jpg
Q: When I use filters, I get too many files!
A: You are using too large a filter, for example .html will get ALL html files identified. If you want to get all files on an address, use www./.html. There are lots of possibilities using filters.
Example:httrack www.all.net +.www.all.net/.htm*
Q: When I use filters, I can't access another domain, but I have filtered it!
A: You may have done a mistake declaring filters, for example +www.all.net/ -all will not work, because -all* has an upper priority (because it has been declared after +www.all.net)
Q: Must I add a '+' or '-' in the filter list when I want to use filters?
A: YES. '+' is for accepting links and '-' to avoid
them. If you forget it, HTTrack will consider that you want to accept a
filter if there is a wild card in the syntax - e.g. +
Q: I want to find file(s) in a web-site. How do I do it?
A: You can use the filters: forbid all files (add a
- in the filter list) and accept only html files and the file(s)
you want to retrieve (BUT do not forget to add
+
Example:httrack www.all.net +www.all.net/*.htm* +thefileiwant.zip
Q: I want to download ftp files/ftp site. How to do?
A: First, HTTrack is not the best tool to download many ftp files. Its ftp engine is basic (even if reget are possible) and if your purpose is to download a complete site, use a specific client.
You can download ftp files just by typing the URL, such as ftp://ftp.www.all.net/pub/files/file010.zip and list ftp directories like ftp://ftp.www.all.net/pub/files/ .
Note: For the filters, use something like +ftp://ftp.www.all.net/*
Q: How can I retrieve .asp or .cgi sources instead of .html result?
A: You can't! For security reasons, web servers do not allow that.
Q: How can I remove these annoying from html files?
A: Use the footer option (-&F, or see the WinHTTrack options)
Q: Do I have to select between ascii/binary transfer mode?
A: No, http files are always transfered as binary files. Ftp files, too (even if ascii mode could be selected)
Q: Can HTTrack perform form-based authentication?
A: Yes. See the URL capture abilities (--catchurl for command-line release, or in the WinHTTrack interface)
Q: Can I redirect downloads to tar/zip archive?
A: Yes. See the shell system command option (-V option for command-line release)
Q: Can I use username/password authentication on a site?
A: Yes. Use user:password@your_url (example: http://foo:bar@www.all.net/private/mybox.html)
Q: Can I use username/password authentication for a proxy?
A: Yes. Use user:password@your_proxy_name as your proxy name (example: smith:foo@proxy.mycorp.com)
Q: Can HTTrack generates HP-UX or ISO9660 compatible files?
A: Yes. See the build options (-N, or see the WinHTTrack options)
Q: If there any SOCKS support?
A: Not yet!
Q: What's this hts-cache directory? Can I remove it?
A: NO if you want to update the site, because this directory is used by HTTrack for this purpose. If you remove it, options and URLs will not be available for updating the site
Q: Can I start a mirror from my bookmarks?
A: Yes. Drag&Drop your bookmark.html file to the WinHTTrack window (or use file://filename for command-line release) and select bookmark mirroring (mirror all links in pages, -Y) or bookmark testing (--testlinks)
Q: I am getting a "pipe broken" error and the mirror stops, what should I do?
A: Chances are this is a result of downloading too
many pages at a time. Remote servers may not allow or be able to handle
too many sessions, or your system may be unable to provide the necessary
resources. Try redusing this number - for example using the -c2 options
for only 2 simultaneous sesions.
`---
title: Storybook
template: docs
excerpt: "Storybook is a great tool for developing and demoing components. "
Storybook
Storybook is a great tool for developing and demoing components. By default, it is based on Webpack and Webpack dev server.
The @web/dev-server-storybook plugin uses an opinionated build of Storybook, making it possible to use it with Web Dev Server for es modules and buildless workflows.
Everyday use
- In Bash, use Tab to complete arguments or list all available commands and ctrl-r to search through command history (after pressing, type to search, press ctrl-r repeatedly to cycle through more matches, press Enter to execute the found command, or hit the right arrow to put the result in the current line to allow editing). -
- In Bash, use ctrl-w to delete the last word, and ctrl-u to delete the content from current curso -
- Alternatively, if you love vi-style key-bindings, use
set -o vi(andset -o emacsto put it back). - - For editing long commands, after setting your editor (f -
To see recent commands, use
history. Follow with!n(wherenis the command number) to execute again. There are also many abbreviations you can use, the most useful probably being!$for last argument and!!for last command (see "HISTORY EXPANSION" in the man page). However, these are often easily replaced with ctrl-r and alt-..Go to your home directory with
cd. Access files relative to your home directory with the~prefix (e.g.~/.bashrc). Inshscripts refer to the home directory as$HOME.To go back to the previous working directory:
cd -.If you are halfway through typing a command but change your mind, hit alt-# to add a
#at the beginning and enter it as a comment (or use ctrl-a, #, enter). You can then return to it later via command history.Use
xargs(orparallel). It's very powerful. Note you can control how many items execute per line (-L) as well as parallelism (-P). If you're not sure if it'll do the right thing, usexargs echofirst. Also,-I{}is handy. Examples:
find . -name '*.py' | xargs grep some_function
cat hosts | xargs -I{} ssh root@{} hostname
pstree -pis a helpful display of the process tree. -- Use
pgrepandpkillto find or signal processes by name (-fis helpful). - - Know the various signals you can send processes. For example, to suspend a process, use
kill -STOP [pid]. For the full list, seeman 7 signal- - Use
nohupordisownif you want a background process to keep ru - - Check what processes are listening via
netstat -lntporss -plat(for TCP; add-ufor UDP) orlsof -iTCP -sTCP:LISTEN -P -n(which also works on macOS). - - See also
lsofandfuserfor open sockets and files. - See
uptimeorwto know how long the system has been running.Use
aliasto create shortcuts for commonly used commands. For example,alias ll='ls -latr'creates a new aliasll.Save aliases, shell settings, and functions you commonly use in
~/.bashrc, and arrange for login shells to source it. This will make your setup available in all your shell sessions.Put the settings of environment variables as well as commands that should be executed when you login in
~/.bash_profile. Separate configuration will be needed for shells you launch from graphical environment logins andcronjobs.Synchronize your configuration files (e.g.
.bashrcand.bash_profile) among various computers with Git.Understand that care is needed when variables and filenames include whitespace. Surround your Bash variables with quotes, e.g.
"$FOO". Prefer the-0or-print0options to enable null characters to delimit filenames, e.g.locate -0 pattern | xargs -0 ls -alorfind / -print0 -type d | xargs -0 ls -al. To iterate on filenames containing whitespace in a for loop, set your IFS to be a newline only usingIFS=$'\n'.In Bash scripts, use
set -x(or the variantset -v, which logs raw input, including unexpanded variables and comments) for debugging output. Use strict modes unless you have a good reason not to: Useset -eto abort on errors (nonzero exit code). Useset -uto detect unset variable usages. Considerset -o pipefailtoo, to abort on errors within pipes (though read up on it more if you do, as this topic is a bit subtle). For more involved scripts, also usetrapon EXIT or ERR. A useful habit is to start a script like this, which will make it detect and abort on common errors and print a message:
set -euo pipefail
trap "echo 'error: Script failed: see failed command above'" ERR
- In Bash scripts, subshells (written with parentheses) are convenient ways to group commands. A common example is to temporarily move to a different working directory, e.g.
# do something in current dir
(cd /some/other/dir && other-command)
# continue in original dir
- In Bash, note there are lots of kinds of variable expansion. Checking a variable exists:
${name:?error message}. For example, if a Bash script requires a single argument, just writeinput_file=${1:?usage: $0 input_file}. Using a default value if a variable is empty:${name:-default}. If you want to have an additional (optional) parameter added to the previous example, you can use something likeoutput_file=${2:-logfile}. If$2is omitted and thus empty,output_filewill be set tologfile. Arithmetic expansion:i=$(( (i + 1) % 5 )). Sequences:{1..10}. Trimming of strings:${var%suffix}and${var#prefix}. For example ifvar=foo.pdf, thenecho ${var%.pdf}.txtprintsfoo.txt. - - Brace expansion using
{...}can reduce having to re-type similar text and automate combinations of items. This is helpful in examples likemv foo.{txt,pdf} some-dir(which moves both files),cp somefile{,.bak}(which expands tocp somefile somefile.bak) ormkdir -p test-{a,b,c}/subtest-{1,2,3}(which expands all possible combinations and creates a directory tree). Brace expansion is performe - The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion. (For example, a range like
{1..20}cannot be expressed with variables using{$a..$b}. Useseqor aforloop instead, e.g.,seq $a $borfor((i=a; i<=b; i++)); do ... ; done.)The output of a command can be treated like a file via
<(some command)(known as process substitution). For example, compare local/etc/hostswith a remote one:
diff /etc/hosts <(ssh somehost cat /etc/hosts)
- When writing scripts you may want to put all of your code in curly braces. If the closing brace is missing, your script will be prevented from executing due to a syntax error. This makes sense when your script is going to be downloaded from the web, since it prevents partially downloaded scripts from executing:
{
# Your code here
}
- A "here document" allows redirection of multiple lines of input as if from a file:
cat <<EOF
input
on multiple lines
EOF
- In Bash, redirect both standard output and standard error via:
some-command >logfile 2>&1orsome-command &>logfile. Often, to ensure a command does not leave an open file handle to standard input, tying it to the terminal you are in, it is also good practice to add</dev/null. - - Use
man asciifor a good ASCII table, with hex and decimal values. For general encoding info,man unicode,man utf-8, andman latin1are helpful. - Use
screenortmuxto multiplex the screen, especially useful on remote ssh sessions and to detach and re-attach to a session.byobucan enhance screen or tmux by providing more information and easier management. A more minimal alternative for session persistence only isdtach.In ssh, knowing how to port tunnel with
-Lor-D(and occasionally-R) is useful, e.g. to access web sites from a remote server.It can be useful to make a few optimizations to your ssh configuration; for example, this
~/.ssh/configcontains settings to avoid dropped connections in certain network environments, uses compression (which is helpful with scp over low-bandwidth connections), and multiplex channels to the same server with a local control file:
TCPKeepAlive=yes
ServerAliveInterval=15
ServerAliveCountMax=6
Compression=yes
ControlMaster auto
ControlPath /tmp/%r@%h:%p
ControlPersist yes
- A few other options relevant to ssh are security sensitive and should be enabled with care, e.g. per subnet or host or in trusted networks:
StrictHostKeyChecking=no,ForwardAgent=yes- Consider
moshan alternative to ssh that uses UDP, avoiding dropped connections and adding convenience on the road (requires server-side setup).To get the permissions on a file in octal form, which is useful for system configuration but not available in
lsand easy to bungle, use something like
stat -c '%A %a %n' /etc/timezone
- For interactive selection of values from the output of another command, use
percolorfzf. - For interaction with files based on the output of another command (like
git), usefpp(PathPicker).For a simple web server for all files in the current directory (and subdirs), available to anyone on your network, use:
python -m SimpleHTTPServer 7777(for port 7777 and Python 2) andpython -m http.server 7777(for port 7777 and Python 3).For running a command as another user, use
sudo. Defaults to running as root; use-uto specify another user. Use-ito login as that user (you will be asked for your password). -- For switching the shell to another user, use
su usernameorsu - username. The latter with "-" gets an environment as if another user just logged in. Omitting the username defaults to root. You will be asked for the password of the user you are switching to. - Know about the 128K limit on command lines. This "Argument list too long" error is common when wildcard matching large numbers of files. (When this happens alternatives like
findandxargsmay help.)For a basic calculator (and of course access to Python in general), use the
pythoninterpreter. For example,
>>> 2+3
5
Processing files and data
- To locate a file by name in the current directory,
find . -iname '*something*'(or similar). To find a file anywhere by name, uselocate something(but bear in mindupdatedbmay not have indexed recently created files). - - For general searching through source or data f -
- To convert HTML to text:
lynx -dump -stdin- - For Markdown, HTML, and all kinds of document conversion, -
- If you must handle XML,
xmlstarletis old but good. - - For JSON, use
jq. For interactive use, also see [jid](https://github.com/si - - For YAML, use
shyaml. - - For Excel or CSV files, csvkit provides
in2csv,csvcut,csvjoin,csvgrep, etc. - - For Amazon S3,
s3cmdis convenient and [s4cmd](https://gi - Know about
sortanduniq, including uniq's-uand-doptions -- see one-liners below. See alsocomm.Know about
cut,paste, andjointo manipulate text files. Many people usecutbut forget aboutjoin.Know about
wcto count newlines (-l), characters (-m), words (-w) and bytes (-c).Know about
teeto copy from stdin to a file and also to stdout, as inls -al | tee file.txt.For more complex calculations, including grouping, reversing fields, and statistical calculations, consider
datamash.Know that locale affects a lot of command line tools in subtle ways, including sorting order (collation) and performance. Most Linux installations will set
LANGor other locale variables to a local setting like US English. But be aware sorting will change if you change locale. And know i18n routines can make sort or other commands run many times slower. In some situations (such as the set operations or uniqueness operations below) you can safely ignore slow i18n routines entirely and use traditional byte-based sort order, usingexport LC_ALL=C.You can set a specific command's environment by prefixing its invocation with the environment variable settings, as in
TZ=Pacific/Fiji date.Know basic
awkandsedfor simple data munging. See One-liners for examples.To replace all occurrences of a string in place, in one or more files:
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
- To rename multiple files and/or search and replace within files, try
repren. (In some cases therenamecommand also allows multiple renames, but be careful as its functionality is not the same on all Linux distributions.)
# Full rename of filenames, directories, and contents foo -> bar:
repren --full --preserve-case --from foo --to bar .
# Recover backup files whatever.bak -> whatever:
repren --renames --from '(.*)\.bak' --to '\1' *.bak
# Same as above, using rename, if available:
rename 's/\.bak$//' *.bak
- As the man page says,
rsyncreally is a fast and extraordinarily versatile file copying tool. It's known for synchronizing between machines but is equally useful locally. When security restrictions allow, usingrsyncinstead ofscpallows recovery of a transfer without restarting from scratch. It also is among the fastest ways to delete large numbers of files:
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
- For monitoring progress when processing files, use
pv,pycp,pmonitor,progress,rsync --progress, or, for block-level copying,dd status=progress. - - Use
shufto shuffle or select random lines from a file. - - Know
sort's options. For numbers, use-n, or-hfor handling human-readable numbers (e.g. fromdu -h). Know how keys work (-tand-k). In particular, watch out that you need to write-k1,1to sort by only the first field;-k1means sort according to the whole line. Stable sort (sort -s) ca - - If you ever need to write a tab literal in a command line in Bash (e.g. for the -t -
The standard tools for patching source code are
diffandpatch. See alsodiffstatfor summary statistics of a diff andsdifffor a side-by-side diff. Notediff -rworks for entire directories. Usediff -r tree1 tree2 | diffstatfor a summary of changes. Usevimdiffto compare and edit files.For binary files, use
hd,hexdumporxxdfor simple hex dumps andbvi,hexeditorbiewfor binary editing.Also for binary files,
strings(plusgrep, etc.) lets you find bits of text.For binary diffs (delta compression), use
xdelta3.To convert text encodings, try
iconv. Oruconvfor more advanced use; it supports some advanced Unicode things. For example:
# Displays hex codes or actual names of characters (useful for debugging):
uconv -f utf-8 -t utf-8 -x '::Any-Hex;' < input.txt
uconv -f utf-8 -t utf-8 -x '::Any-Name;' < input.txt
# Lowercase and removes all accents (by expanding and dropping them):
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC;' < input.txt > output.txt
- To split files into pieces, see
split(to split by size) andcsplit(to split by a pattern). - - Date and time: To get the current date and time in the helpful [ISO 8601](h -
Use
zless,zmore,zcat, andzgrepto operate on compressed files.File attributes are settable via
chattrand offer a lower-level alternative to file permissions. For example, to protect against accidental file deletion the immutable flag:sudo chattr +i /critical/directory/or/fileUse
getfaclandsetfaclto save and restore file permissions. For example:
getfacl -R /some/path > permissions.txt
setfacl --restore=permissions.txt
- To create empty files quickly, use
truncate(creates sparse file),fallocate(ext4, xfs, btrfs and ocfs2 filesystems),xfs_mkfile(almost any filesystems, comes in xfsprogs package),mkfile(for Unix-like systems like Solaris, Mac OS).
System debugging
- For web debugging,
curlandcurl -Iare handy, or theirwgetequivalents, or the more modernhttpie. - - To know current cpu/disk status, the classic tools are `t -
- For network connection details, use
netstatandss. - - For a quick overview of what's happening on a system,
dstatis especially useful. For broades - - To know memory status, run and understand the output of
freeandvmstat. In particular, be aware the "cached" value is memory held by the Linux kernel a - - Java system debugging is a different kettle of fish, but a simple trick on Oracle's and some other JVMs is that you can run
kill -3 <pid>and a full stack trace and heap summary (including generational - - Use
mtras a better traceroute, to identify network issues. - - For looking at why a disk is full,
ncdusaves time over the usual commands likedu -sh *. - - To find which socket or process is using bandwidth, try
iftopornethogs. - - The
abtool (comes with Apache) is helpful for quick-and-dirty checking of web server perform - For more serious network debugging,
wireshark,tshark, orngrep.Know about
straceandltrace. These can be helpful if a program is failing, hanging, or crashing, and you don't know why, or if you want to get a general idea of performance. Note the profiling option (-c), and the ability to attach to a running process (-p). Use trace child option (-f) to avoid missing important calls.Know about
lddto check shared libraries etc â but never run it on untrusted files.Know how to connect to a running process with
gdband get its stack traces.Use
/proc. It's amazingly helpful sometimes when debugging live problems. Examples:/proc/cpuinfo,/proc/meminfo,/proc/cmdline,/proc/xxx/cwd,/proc/xxx/exe,/proc/xxx/fd/,/proc/xxx/smaps(wherexxxis the process id or pid).When debugging why something went wrong in the past,
sarcan be very helpful. It shows historic statistics on CPU, memory, network, etc.For deeper systems and performance analyses, look at
stap(SystemTap),perf, andsysdig.Check what OS you're on with
unameoruname -a(general Unix/kernel info) orlsb_release -a(Linux distro info).Use
dmesgwhenever something's acting really funny (it could be hardware or driver issues).If you delete a file and it doesn't free up expected disk space as reported by
du, check whether the file is in use by a process:lsof | grep deleted | grep "filename-of-my-big-file"
One-liners
A few examples of piecing together commands:
- It is remarkably helpful sometimes that you can do set intersection, union, and difference of text files via
sort/uniq. Supposeaandbare text files that are already uniqued. This is fast, and works on files of arbitrary size, up to many gigabytes. (Sort is not limited by memory, though you may need to use the-Toption if/tmpis on a small root partition.) See also the note aboutLC_ALLabove andsort's-uoption (left out for clarity below).
sort a b | uniq > c # c is a union b
sort a b | uniq -d > c # c is a intersect b
sort a b b | uniq -u > c # c is set difference a - b
- Pretty-print two JSON files, normalizing their syntax, then coloring and paginating the result:
diff <(jq --sort-keys . < file1.json) <(jq --sort-keys . < file2.json) | colordiff | less -R
- Use
grep . *to quickly examine the contents of all files in a directory (so each line is paired with the filename), orhead -100 *(so each file has a heading). This can be useful for directories filled with config settings like those in/sys,/proc,/etc. - - Summing all numbers in the third column of a text file (this is probably 3X faster and 3X less code than equivalent Python):
awk '{ x += $3 } END { print x }' myfile
- To see sizes/dates on a tree of files, this is like a recursive
ls -lbut is easier to read thanls -lR:
find . -type f -ls
- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an
acct_idparameter that is present in the URL. If you want a tally of how many requests for eachacct_id:
egrep -o 'acct_id=[0-9]+' access.log | cut -d= -f2 | sort | uniq -c | sort -rn
- To continuously monitor changes, use
watch, e.g. check changes to files in a directory withwatch -d -n 2 'ls -rtlh | tail'or to network settings while troubleshooting your wifi settings withwatch -d -n 2 ifconfig. - - Run this function to get a random tip from this document (parses Markdown and extracts an item):
function taocl() {
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
sed '/cowsay[.]png/d' |
pandoc -f markdown -t html |
xmlstarlet fo --html --dropdtd |
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
xmlstarlet unesc | fmt -80 | iconv -t US
}
Obscure but useful
expr: perform arithmetic or boolean operations or evaluate regular expressions -m4: simple macro processor -yes: print a string a lot -cal: nice calendar -env: run a command (useful in -printenv: print out enviro -look: find English words (or lines in a file) beginning -cut,pasteand `jo -fmt: format text paragrap -pr: format text into pages/colum -fold: wrap lines of text -column: format text fields into aligned, f -expandandunexpand: convert between tabs and spaces -nl: add line numbers -seq: print numbers -bc: calculator -factor: factor integers -gpg: encrypt and si -toe: table of terminfo entries -nc: network debugging and data transfer -socat: socket relay and tcp port -- [
slurm](https://github.com/ - dd: moving data between files or devices -file: identify type of a file -tree: display directories and subdirectories as a nesting tree; -stat: file info -time: execute and time a command -timeout: execute a command for specified amount of time and stop the process when the s -lockfile: create semaphor -logrotate: rotate, compress and -watch: run a command -when-changed: runs any command you spe -tac: print files in rev -comm: compare sorted files line by line -strings: extract text from binary files -tr: character translation or manipulation -iconvoruconv: conversion for text encodingssplitandcsplit: splitting filessponge: read all input before writing it, useful for reading from then writing to the same file, e.g.,grep -v something some-file | sponge some-fileunits: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also/usr/share/units/definitions.units)apg: generates random passwordsxz: high-ratio file compressionldd: dynamic library infonm: symbols from object filesaborwrk: benchmarking web serversstrace: system call debuggingmtr: better traceroute for network debuggingcssh: visual concurrent shellrsync: sync files and folders over SSH or in local file systemngrep: grep for the network layerhostanddig: DNS lookupslsof: process file descriptor and socket infodstat: useful system statsglances: high level, multi-subsystem overviewiostat: Disk usage statsmpstat: CPU usage statsvmstat: Memory usage statshtop: improved version of toplast: login historyw: who's logged onid: user/group identity infosar: historic system statsss: socket statisticsdmesg: boot and system error messagessysctl: view and configure Linux kernel parameters at run timehdparm: SATA/ATA disk manipulation/performancelsblk: list block devices: a tree view of your disks and disk partitionslshw,lscpu,lspci,lsusb,dmidecode: hardware information, including CPU, BIOS, RAID, graphics, devices, etc.lsmodandmodinfo: List and show details of kernel modules.fortune,ddate, andsl: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful"
macOS only
These are items relevant only on macOS.
- Package management with
brew(Homebrew) and/orport(MacPorts). These can be used to install on macOS many of the above commands. - - Copy output of any command to a desktop app with
pbcopyand paste input from one withpbpaste. - - To enable the Option key in macOS Terminal as an alt key (such as used in the commands above lik -
To open a file with a desktop app, use
openoropen -a /Applications/Whatever.app.Spotlight: Search files with
mdfindand list metadata (such as photo EXIF info) withmdls.Be aware macOS is based on BSD Unix, and many commands (for example
ps,ls,tail,awk,sed) have many subtle variations from Linux, which is largely influenced by System V-style Unix and GNU tools. You can often tell the difference by noting a man page has the heading "BSD General Commands Manual." In some cases GNU versions can be installed, too (such asgawkandgsedfor GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python orperl) or test carefully.To get macOS release information, use
sw_vers.
Windows only
These items are relevant only on Windows.
Ways to obtain Unix tools under Windows
- Access the power of the Unix shell under Microsoft Windows by installing Cygwin. Most of the things described in this document will work out of the box. -
- On Windows 10, you can use Windows Subsystem for Linux (WSL), which provides a familiar Bash environment with Unix command line utilities. -
If you mainly want to use GNU developer tools (such as GCC) on Windows, consider MinGW and its MSYS package, which provides utilities such as bash, gawk, make and grep. MSYS doesn't have all the features compared to Cygwin. MinGW is particularly useful for creating native Windows ports of Unix tools.
Another option to get Unix look and feel under Windows is Cash. Note that only very few Unix commands and command-line options are available in this environment.
Useful Windows command-line tools
- You can perform and script most Windows system administration tasks from the command line by learning and using
wmic. - Native command-line Windows networking tools you may find useful include
ping,ipconfig,tracert, andnetstat.You can perform many useful Windows tasks by invoking the
Rundll32command.
Cygwin tips and tricks
- Install additional Unix programs with the Cygwin's package manager. -
- Use
minttyas your command-line window. - - Access the Windows clipboard through `/dev/cl -
Run
cygstartto open an arbitrary file through its registered application.Access the Windows registry with
regtool.Note that a
C:\Windows drive path becomes/cygdrive/cunder Cygwin, and that Cygwin's/appears underC:\cygwinon Windows. Convert between Cygwin and Windows-style file paths withcygpath. This is most useful in scripts that invoke Windows programs.
More resources
- awesome-shell: A curated list of shell tools and resources.
- awesome-osx-command-line: A more in-depth guide for the macOS command line.
- Strict mode for writing better shell scripts.
- shellcheck: A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
- Filenames and Pathnames in Shell: The sadly complex minutiae on how to handle filenames correctly in shell scripts.
- Data Science at the Command Line: More commands and tools helpful for doing data science, from the book of the same name
title: Bash Commands Tutorial weight: 0 excerpt: Here's a list of bash commands that stand between me and insanity. seo: title: 'Bash Commands Tutorial' description: 'Bash Commands That Save Me Time and Frustration' robots: [] extra: [] type: stackbit_page_meta
template: docs
Bash Commands That Save Me Time and Frustration
Here's a list of bash commands that stand between me and insanity.
Bash Commands That Save Me Time and Frustration
Here's a list of bash commands that stand between me and insanity
This article will be accompanied by the following github repository which will contain all the commands listed as well as folders that demonstrate before and after usage!
bgoonz/bash-commands-walkthrough\ to accompany the medium article I am writing. Contribute to bgoonz/bash-commands-walkthrough development by creating an...github.com
The readme for this git repo will provide a much more condensed list... whereas this article will break up the commands with explanations... images & links!
I will include the code examples as both github gists (for proper syntax highlighting) and as code snippets adjacent to said gists so that they can easily be copied and pasted... or ... if you're like me for instance; and like to use an extension to grab the markdown content of a page... the code will be included rather than just a link to the gist!
Here's a Cheatsheet
Getting Started (Advanced Users Skip Section)
â Check the Current Directory ⥠pwd
On the command line, it's important to know the directory we are currently working on. For that, we can use pwd command.
It shows that I'm working on my Desktop directory.
â Display List of Files ⥠ls
To see the list of files and directories in the current directory use ls command in your CLI.
Shows all of my files and directories of my Desktop directory.
- To show the contents of a directory pass the directory name to the
lscommand i.e.ls directory_name. - Some useful
lscommand options:-
OptionDescriptionls -alist all files including hidden file starting with '.'ls -llist with the long formatls -lalist long format including hidden files
â Create a Directory ⥠mkdir
We can create a new folder using the mkdir command. To use it type mkdir folder_name.
Use ls command to see the directory is created or not.
I created a cli-practice directory in my working directory i.e. Desktop directory.
â Move Between Directories ⥠cd
It's used to change directory or to move other directories. To use it type cd directory_name.
Can use pwd command to confirm your directory name.
Changed my directory to the cli-practice directory. And the rest of the tutorial I'm gonna work within this directory.
â Parent Directory ⥠..
We have seen cd command to change directory but if we want to move back or want to move to the parent directory we can use a special symbol .. after cd command, like cd ..
â Create Files ⥠touch
We can create an empty file by typing touch file_name. It's going to create a new file in the current directory (the directory you are currently in) with your provided name.
I created a hello.txt file in my current working directory. Again you can use ls command to see the file is created or not.
Now open your hello.txt file in your text editor and write Hello Everyone! into your hello.txt file and save it.
â Display the Content of a File ⥠cat
We can display the content of a file using the cat command. To use it type cat file_name.
Shows the content of my hello.txt file.
â Move Files & Directories ⥠mv
To move a file and directory, we use mv command.
By typing mv file_to_move destination_directory, you can move a file to the specified directory.
By entering mv directory_to_move destination_directory, you can move all the files and directories under that directory.
Before using this command, we are going to create two more directories and another txt file in our cli-practice directory.
mkdir html css touch bye.txt
Yes, we can use multiple directories & files names one after another to create multiple directories & files in one command.
Moved my bye.txt file into my css directory and then moved my css directory into my html directory.
â Rename Files & Directories ⥠mv
mv command can also be used to rename a file and a directory.
You can rename a file by typing mv old_file_name new_file_name & also rename a directory by typing mv old_directory_name new_directory_name.
Renamed my hello.txt file to the hi.txt file and html directory to the folder directory.
â Copy Files & Directories ⥠cp
To do this, we use the cp command.
- You can copy a file by entering
cp file_to_copy new_file_name.
Copied my hi.txt file content into hello.txt file. For confirmation open your hello.txt file in your text editor.
- You can also copy a directory by adding the
-roption, likecp -r directory_to_copy new_directory_name.
The -r option for "recursive" means that it will copy all of the files including the files inside of subfolders.
Here I copied all of the files from the folder to folder-copy.
â Remove Files & Directories ⥠rm
To do this, we use the rm command.
- To remove a file, you can use the command like
rm file_to_remove.
Here I removed my hi.txt file.
- To remove a directory, use the command like
rm -r directory_to_remove.
I removed my folder-copy directory from my cli-practice directory i.e. current working directory.
â Clear Screen ⥠clear
Clear command is used to clear the terminal screen.
â Home Directory ⥠~
The Home directory is represented by ~. The Home directory refers to the base directory for the user. If we want to move to the Home directory we can use cd ~ command. Or we can only use cd command.
MY COMMANDS
1.) Recursively unzip zip files and then delete the archives when finished
here is a folder containing the before and after... I had to change folder names slightly due to a limit on the length of file-paths in a github repo.
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;
find . -name "*.zip" -type f -print -delete
2.) Install node modules recursively
npm i -g recursive-install
npm-recursive-install
3.) Clean up unnecessary files/folders in git repo
find . -empty -type f -print -delete #Remove empty files
# -------------------------------------------------------
find . -empty -type d -print -delete #Remove empty folders
# -------------------------------------------------------
# This will remove .git folders... .gitmodule files as well as .gitattributes and .gitignore files.
find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} +
# -------------------------------------------------------
# This will remove the filenames you see listed below that just take up space if a repo has been downloaded for use exclusively in your personal file system (in which case the following files just take up space)# Disclaimer... you should not use this command in a repo that you intend to use with your work as it removes files that attribute the work to their original creators!
find . \( -name "*SECURITY.txt" -o -name "*RELEASE.txt" -o -name "*CHANGELOG.txt" -o -name "*LICENSE.txt" -o -name "*CONTRIBUTING.txt" -name "*HISTORY.md" -o -name "*LICENSE" -o -name "*SECURITY.md" -o -name "*RELEASE.md" -o -name "*CHANGELOG.md" -o -name "*LICENSE.md" -o -name "*CODE_OF_CONDUCT.md" -o -name "\*CONTRIBUTING.md" \) -exec rm -rf -- {} +
In Action
The following output from my bash shell corresponds to the directory:
bgoonz/bash-commands-walkthrough\ Deployment github-pages Navigation Big O notation is the language we use for talking about how long an algorithm takes...github.com
which was created by running the aforementioned commands in in a perfect copy of this directory
bgoonz/DS-ALGO-OFFICIAL\ Deployment github-pages Navigation Big O notation is the language we use for talking about how long an algorithm takes...github.com
.....below is the terminal output for the following commands:
pwd
/mnt/c/Users/bryan/Downloads/bash-commands/steps/3-clean-up-fluf/DS-ALGO-OFFICIAL-master
After printing the working directory for good measure:
find . -empty -type f -print -delete
The above command deletes empty files recursively starting from the directory in which it was run:
./CONTENT/DS-n-Algos/File-System/file-utilities/node_modules/line-reader/test/data/empty_file.txt
./CONTENT/DS-n-Algos/_Extra-Practice/free-code-camp/nodejs/http-collect.js
./CONTENT/Resources/Comments/node_modules/mime/.npmignore
./markdown/tree2.md
./node_modules/loadashes6/lodash/README.md
./node_modules/loadashes6/lodash/release.md
./node_modules/web-dev-utils/Markdown-Templates/Markdown-Templates-master/filled-out-readme.md
|01:33:16|bryan@LAPTOP-9LGJ3JGS:[DS-ALGO-OFFICIAL-master] DS-ALGO-OFFICIAL-master_exitstatus:0[â___________o>
The command seen below deletes empty folders recursively starting from the directory in which it was run:
find . -empty -type d -print -delete
The resulting directories....
|01:33:16|bryan@LAPTOP-9LGJ3JGS:[DS-ALGO-OFFICIAL-master] DS-ALGO-OFFICIAL-master_exitstatus:0[â___________o>
find . -empty -type d -print -delete
./.git/branches
./.git/objects/info
./.git/refs/tags
|01:33:31|bryan@LAPTOP-9LGJ3JGS:[DS-ALGO-OFFICIAL-master] DS-ALGO-OFFICIAL-master_exitstatus:0[â___________o>
The command seen below deletes .git folders as well as .gitignore, .gitattributes, .gitmodule files
find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} +
The command seen below deletes most SECURITY, RELEASE, CHANGELOG, LICENSE, CONTRIBUTING, & HISTORY files that take up pointless space in repo's you wish to keep exclusively for your own reference.
!!!Use with caution as this command removes the attribution of the work from it's original authors
!!!Use with caution as this command removes the attribution of the work from it's original authors!!!!!find . ( -name "SECURITY.txt" -o -name "RELEASE.txt" -o -name "CHANGELOG.txt" -o -name "LICENSE.txt" -o -name "CONTRIBUTING.txt" -name "HISTORY.md" -o -name "LICENSE" -o -name "SECURITY.md" -o -name "RELEASE.md" -o -name "CHANGELOG.md" -o -name "LICENSE.md" -o -name "CODE_OF_CONDUCT.md" -o -name "*CONTRIBUTING.md" ) -exec rm -rf -- {} +
4.) Generate index.html file that links to all other files in working directory
#!/bin/sh
# find ./ | grep -i "\.*$" >files
find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$">files
listing="files"
out=""
html="index.html"
out="basename $out.html"
html="index.html"
cmd() {
echo ' <!DOCTYPE html>'
echo '<html>'
echo '<head>'
echo ' <meta http-equiv="Content-Type" content="text/html">'
echo ' <meta name="Author" content="Bryan Guner">'
echo '<link rel="stylesheet" href="./assets/prism.css">'
echo ' <link rel="stylesheet" href="./assets/style.css">'
echo ' <script async defer src="./assets/prism.js">
</script>'
echo " <title> directory </title>"
echo ""
echo '<style>'
echo ' a {'
echo ' color: black;'
echo ' }'
echo ''
echo ' li {'
echo ' border: 1px solid black !important;'
echo ' font-size: 20px;'
echo ' letter-spacing: 0px;'
echo ' font-weight: 700;'
echo ' line-height: 16px;'
echo ' text-decoration: none !important;'
echo ' text-transform: uppercase;'
echo ' background: #194ccdaf !important;'
echo ' color: black !important;'
echo ' border: none;'
echo ' cursor: pointer;'
echo ' justify-content: center;'
echo ' padding: 30px 60px;'
echo ' height: 48px;'
echo ' text-align: center;'
echo ' white-space: normal;'
echo ' border-radius: 10px;'
echo ' min-width: 45em;'
echo ' padding: 1.2em 1em 0;'
echo ' box-shadow: 0 0 5px;'
echo ' margin: 1em;'
echo ' display: grid;'
echo ' -webkit-border-radius: 10px;'
echo ' -moz-border-radius: 10px;'
echo ' -ms-border-radius: 10px;'
echo ' -o-border-radius: 10px;'
echo ' }'
echo ' </style>'
echo '</head>'
echo '<body>'
echo ""
# continue with the HTML stuff
echo ""
echo ""
echo "<ul>"
awk '{print "<li>
<a href=\""$1"\">",$1," </a>
</li>"}' $listing
# awk '{print "<li>"};
# {print " <a href=\""$1"\">",$1,"</a>
</li> "}' \ $listing
echo ""
echo "</ul>"
echo "</body>"
echo "</html>"
}
cmd $listing --sort=extension >>$html
In Action
I will use this copy of my Data Structures Practice Site to demonstrate the result:
side-projects-42/DS-Bash-Examples-Deploy\ Deployment github-pages Navigation Big O notation is the language we use for talking about how long an algorithm takes...github.com
The result is a index.html file that contains a list of links to each file in the directory
here is a link to and photo of the resulting html file:
index.html\ CONTENT/DS-n-Algos/quirky-meninsky-4181b5.netlify.app
5.) Download all links to a files of a specified extension on a user provided (url) webpage
wget -r -A.pdf https://overapi.com/gitwget --wait=2 --level=inf --limit-rate=20K --recursive --page-requisites --user-agent=Mozilla --no-parent --convert-links --adjust-extension --no-clobber -e robots=off
The result is stored in this directory:
6.)Recursively remove lines of text containing the string badFolder from files in the working directory
find . -type f -exec sed -i '/badFolder/d' ./* {} \;
# OR
find . -name 'result.md' -type f -exec sed -i '/badFolder/d' ./* {} \;
As an example I will run this command on a file containing the text:
Hacks Blog
Read more at hacks.mozilla.org
badFolder
badFolder Implementing Private Fields for JavaScript
When implementing a language feature for JavaScript, an implementer must make decisions about how the language in the specification maps to the implementation. Private fields is an example of where the specification language and implementation reality diverge, at least in SpiderMonkey-- the JavaScript engine which powers Firefox. To understand more, I'll explain what private fields are, a couple of models for thinking about them, and explain why our implementation diverges from the specification language.The post Implementing Private Fields for JavaScript appeared first on Mozilla Hacks - the Web developer blog.
Posted Tuesday, June 8, 2021 by Matthew Gaudet
Looking fine with Firefox 89
Firefox 89 has smartened up and brings with it a slimmed-down, slightly more minimalist interface.badFolder Along with this new look, we get some great styling features including a force-colours feature for media queries and better control over how fonts are displayed. The long-awaited top-level await keyword for JavaScript modules is now enabled, as well as the PerformanceEventTiming interface, which is another addition to the performance suite of APIs: 89 really has been working out!The post Looking fine with Firefox 89 appeared first on Mozilla Hacks - the Web developer blog.
badFolder
Posted Tuesday, June 1, 2021 by Chris Mills
badFolder
Improving Firefox stability on Linux
Roughly a year ago at Mozilla we started an effort to improve Firefox stability on Linux. This effort quickly became an example of good synergies between FOSS projects.The post Improving Firefox stability on Linux appeared first on Mozilla Hacks - the Web developer blog.
Posted Wednesday, May 19, 2021 by Gabriele Svelto badFolder
Introducing Firefox's new Site Isolation Security Architecture
Like any web browser, Firefox loads code from untrusted and potentially hostile websites and runs it on your computer. To protect you against new types of attacks from malicious sites and to meet the security principles of Mozilla, we set out to redesign Firefox on desktop.The post Introducing Firefox's new Site Isolation Security Architecture appeared first on Mozilla Hacks - the Web developer blog.
Posted Tuesday, May 18, 2021 by Anny Gakhokidze
Pyodide Spin Out and 0.17 Release
We are happy to announce that Pyodide has become an independent and community-driven project. We are also pleased to announce the 0.17 release for Pyodide with many new features and improvements. Pyodide consists of the CPython 3.8 interpreter compiled to WebAssembly which allows Python to run in the browser.The post Pyodide Spin Out and 0.17 Release appeared first on Mozilla Hacks - the Web developer blog. badFolder
Posted Thursday, April 22, 2021 by Teon Brooks
I modified the command slightly to apply only to files called 'result.md':
The result is :
Hacks Blog
Read more at hacks.mozilla.org
When implementing a language feature for JavaScript, an implementer must make decisions about how the language in the specification maps to the implementation. Private fields is an example of where the specification language and implementation reality diverge, at least in SpiderMonkey-- the JavaScript engine which powers Firefox. To understand more, I'll explain what private fields are, a couple of models for thinking about them, and explain why our implementation diverges from the specification language.The post Implementing Private Fields for JavaScript appeared first on Mozilla Hacks - the Web developer blog.
Posted Tuesday, June 8, 2021 by Matthew Gaudet
Looking fine with Firefox 89
Posted Tuesday, June 1, 2021 by Chris Mills
Improving Firefox stability on Linux
Roughly a year ago at Mozilla we started an effort to improve Firefox stability on Linux. This effort quickly became an example of good synergies between FOSS projects.The post Improving Firefox stability on Linux appeared first on Mozilla Hacks - the Web developer blog.
Introducing Firefox's new Site Isolation Security Architecture
Like any web browser, Firefox loads code from untrusted and potentially hostile websites and runs it on your computer. To protect you against new types of attacks from malicious sites and to meet the security principles of Mozilla, we set out to redesign Firefox on desktop.The post Introducing Firefox's new Site Isolation Security Architecture appeared first on Mozilla Hacks - the Web developer blog.
Posted Tuesday, May 18, 2021 by Anny Gakhokidze
Pyodide Spin Out and 0.17 Release
Posted Thursday, April 22, 2021 by Teon Brooks
the test.txt and result.md files can be found here:
bgoonz/bash-commands-walkthrough\ to accompany the medium article I am writing. Contribute to bgoonz/bash-commands-walkthrough development by creating an...github.com
7.) Execute command recursively
Here I have modified the command I wish to run recursively to account for the fact that the 'find' command already works recursively, by appending the -maxdepth 1 flag...
I am essentially removing the recursive action of the find command...
That way, if the command affects the more deeply nested folders we know the outer RecurseDirs function we are using to run the find/pandoc line once in every subfolder of the working directory... is working properly!
Run in the folder shown to the left... we would expect every .md file to be accompanied by a newly generated html file by the same name.
The results of said operation can be found in the following directory
In Action
đą Below đą
The final result is
If you want to run any bash script recursively all you have to do is substitue out line #9 with the command you want to run once in every sub-folder.
function RecurseDirs ()
{
oldIFS=$IFS
IFS=$'\n'
for f in "$@"
do
#Replace the line below with your own command!
#find ./ -iname "*.md" -maxdepth 1 -type f -exec sh -c 'pandoc --standalone "${0}" -o "${0%.md}.html"' {} \;
#####################################################
# YOUR CODE BELOW!
#####################################################
if [[ -d "${f}" ]]; then
cd "${f}"
RecurseDirs $(ls -1 ".")
cd ..
fi
done
IFS=$oldIFS
}
RecurseDirs "./"
TBC
Here are some of the other commands I will cover in greater detail... at a later time:

